Home > Net >  Why is does this C code output 1 instead of 0?
Why is does this C code output 1 instead of 0?

Time:10-31

Why does this output 1? If p[i][j] = i j; should'nt it output 0 as when i==0 and j ==0 then p[0][0j] should be 0 as well. When I run this code it outputs 1.

int main(void){
    int i, j;
    int **p = (int **) malloc(2 * sizeof(int*));
    p[0] = (int*)malloc(2*sizeof(int));
    p[1] = p[0];
    
    for(i = 0; i < 2; i  )
        for(j=0; j < 2; j  )
            p[i][j]=i   j;
            
    printf("%d\n", p[0][0]);
    return 0;
}

CodePudding user response:

It may help to draw a picture of the memory layout you end up with here:

    --- 
p: | * |
    -|- 
     |
     V
    ---         --- --- 
   | *-------> | 1 | 2 |
    ---    ,->  --- --- 
   | *----'
    --- 

Since p[0] and p[1] point to the same place, you don't actually get the 2x2 array that the rest of the code seems to suggest.

If you rewrote the allocation code like this:

int **p = (int **) malloc(2 * sizeof(int*));
for(i = 0; i < 2; i  )
    p[i] = (int*)malloc(2*sizeof(int));

then you would end up with memory like this:

    --- 
p: | * |
    -|- 
     |
     V
    ---         --- --- 
   | *-------> | 0 | 1 |
    ---         --- --- 
   | *---.      --- --- 
    ---   `--> | 1 | 2 |
                --- --- 

And now you would find that p[0][0] would be 0.

CodePudding user response:

Because p[1] and p[0] are the same pointer, and therefore p[1][0] is the same object as p[0][0]. So when you have i==1 and j==0, you store 1 to that object, which overwrites the 0 you put there when i==0 and j==0.

  • Related