Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The first int in one of two arrays is assigned 0 when I leave the for loop in which I assigned them values

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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++;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading