- Code: Select all
for(int j = 0; j < sizeof(array); j++)
{
a_int += array[j] * pow(10.0,j);
}
I'm just not getting the results that I want.
Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard
for(int j = 0; j < sizeof(array); j++)
{
a_int += array[j] * pow(10.0,j);
}
int array[]={1,3,4,2,3};
int n=sizeof(array);
int a_int=0;
for(int j=0; j<n; j++)
a_int+=array[j]*pow(10.0,n-j);
What do you mean an array of ints
int array[];
devil_slayer wrote:Maybe you want:
- Code: Select all
int array[]={1,3,4,2,3};
int n=sizeof(array);
int a_int=0;
for(int j=0; j<n; j++)
a_int+=array[j]*pow(10.0,n-j);
int array[]={1,3,4,2,3};
int n=sizeof(array) / sizeof(int);
int a_int=0;
for(int j=0; j<n; j++)
a_int+=array[j]*pow(10.0,n-j);
taymo2020 wrote:Why should I be afraid of overflow?
No it wont. It should just truncate to 0.devil_slayer wrote:taymo2020 wrote:Why should I be afraid of overflow?
Well, what if your array of ints sums up to more then it fits in ine int. Remeber an int can have a max of 2^31 or in other words: 2 147 483 648.
If your array contains more than that the int will overflow.
Can you specify what you are using this for perhaps?
devil_slayer wrote:Can you specify what you are using this for perhaps?
int arrayToInt(int* array)
{
int a_int = 0;
int n = sizeof(array)/sizeof(int);
for(int j = 0; j < n; j++)
{
a_int += array[j] * pow(10.0,j);
}
return (a_int);
}
int array[] = {8,9,9,9,9,9,9,9,9,9,9};
RITZ wrote:You're passing a pointer so sizeof is giving you the size of the pointer.
RITZ wrote:No it wont. It should just truncate to 0.
int c=4;
int d=(int)pow(10,c-2);#include <stdio.h>
int f(int array[],int n)
{
int a_int=0,j;
int tens=1;
for(j=n-1; j>=0; j--)
{
a_int += array[j] * tens;
printf("D:%d\n",a_int);
tens*=10;
}
}
int main()
{
int a[]={4,1,2,3};
printf("%d\n",f(a,4));
return 0;
}
devil_slayer wrote:Can someone please explain why:
- Code: Select all
int c=4;
int d=(int)pow(10,c-2);
gives 99 instead of 100?
By definition that is not an overflow. An overflow is when you write past the end of a buffer into uncharted territories and an overrun is when you read past the end of a buffer. This is the cause of a mathmatical instruction which cannot complete it's routine due to lack of memory. The opposite of a buffer overflow, it avoids a buffer overflow by defaulting to 0.devil_slayer wrote:RITZ wrote:RITZ wrote:No it wont. It should just truncate to 0.
To me that's an overflow. In any case it's a fault in the program.
int sum = 0;
for (int i = 0; i < size; ++i) {
sum = sum * 10 + array[i];
}
Return to Algorithms & Data Structures
Users browsing this forum: No registered users and 1 guest