Question

I can't seem to understand why is this code printing 1 as an answer. I'm in process of learning C and this is one the questions for a homework. Can somebody please explain?

#include <stdio.h>
#include <stdlib.h>
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",p[0][0]);
    return 0;
}

In my opinion is should print 0, but it seems i'm wrong.

Was it helpful?

Solution

You are getting confused with the pointers. p[0] is a pointer to int, so is p[1].

The code makes p[0] and p[1] point to the same address:

p[1] = p[0];

This has the effect that p[i][j] refers to the same object whether i is 0 or 1. The nested loops will access p[0][0] in the first place, setting it to 0, but then later p[1][0] (which is the same object as p[0][0] is accessed, which causes it to be assigned 1.

The key point here is that p[0][0] and p[1][0] are the same.

OTHER TIPS

p[0] and p[1] are both int * type (i.e. pointers). After

p[1] = p[0];

both p[1] and p[0] are pointing to the same address, which makes p[0][0] the same to p[1][0]. The value is determined by which update it last. And p[1][0] updates this value at last, which makes the final result is 1.

If you change your code to:

for(i = 1; i >= 0; i--)
    for(j = 1; j >= 0; j--)
        p[i][j] = i + j;
printf("%d",p[1][0]);

Guess what, it will print 0. Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top