I am chopping off every digit from a long "n" starting with the last and assigning them into two alternating arrays x[] & y[] using a for loop.
I was expecting the first int in the array x[0] to be a non 0 int & when i print inside the loop it gives expected results but if i print after the loop, just the first int of the second array x[0] is 0? everything else works as intended?
int x[8];
int y[8];
long n = 4003600000000014;
int d = 0;
printf("x before: ");
for (long j = n; j > 0; j /= 10)
{
y[d] = n % 10;
n /= 10;
x[d] = n % 10;
// debug to print x
printf("%d, ", x[d]);
n /= 10;
d++;
}
//debug print
printf("\n");
printf("x after: ");
for(int fu = 0; fu < 8; fu++)
{
printf("%d, ", x[fu]);
}
printf("\n");
the long "n" is just a test example it should be able to take any long
>Solution :
The problem is the for loop
for (long j = n; j > 0; j /= 10)
{
y[d] = n % 10;
n /= 10;
x[d] = n % 10;
// debug to print x
printf("%d, ", x[d]);
n /= 10;
d++;
}
It has more iterations then the sizes of the arrays x and y.
In the for loop statement the variable j is divided by 10 only one time in each iteration of the loop
for (long j = n; j > 0; j /= 10)
^^^^^^^
But within the body of the loop the variable n is divided by 10 two times
y[d] = n % 10;
n /= 10;
^^^^^^^^
x[d] = n % 10;
// debug to print x
printf("%d, ", x[d]);
n /= 10;
^^^^^^^
d++;
As a result within the for loop there are accesses of memory beyond the arrays x and y.
You could rewrite your loop the following way
for (long j = n; j > 0; )
{
y[d] = j % 10;
j /= 10;
x[d] = j % 10;
// debug to print x
printf("%d, ", x[d]);
j /= 10;
d++;
}