Unexpected c pointer result -
hi have started learning c pointers , can't understand why getting different pointer value expected. here function
int test(void){ int i,j; int **p = (int **)malloc(2 * sizeof(int *)); p[0] = (int *)malloc(2 * sizeof(int)); printf("p[0] = %d\n",p[0]); p[1] = p[0]; printf("p[1] = %d\n",p[1]); for(i = 0; < 2; i++){ for(j = 0; j < 2; j++) { p[i][j] = + j; printf("p[%d][%d] = %d\n",i,j,p[i][j]); } } printf("result p[0][0] = %d\n",p[0][0]); return 0; }
i expecting p[0][0] = 0 printed loop, equal 1 , value seems coming p[1][0], missing here?
printf output:
p[0] = 1224416 p[1] = 1224416 p[0][0] = 0 p[0][1] = 1 p[1][0] = 1 p[1][1] = 2 result p[0][0] = 1
first -- passing int*
printf()
, expects int
(%d
) , use (%p
) printing address instead.
second --
p[1] = p[0];
the p[0]
, p[1]
pointers both pointing same address. means if modify 1 row (p[0]
), second (p[1]
) modified well.
and root of problem
i expecting p[0][0] = 0 printed loop, equal 1 , value seems coming p1[0], missing here?
+---+---+ | 0 | 0 | +---+---+ ^ ^ | | | -------------------- p[0] ---------------------- p[1]
now modify p[1]
, , looks this. in other words, values 0
, 1
of p[0]
overwritten
+---+---+ | 1 | 2 | +---+---+ ^ ^ | | | -------------------- p[0] ---------------------- p[1]
instead of p[1] = p[0]
, assign p[1]
(different) memory on heap well.
p[0] = malloc(2 * sizeof(int)); p[1] = malloc(2 * sizeof(int));
and p[0][0]
correctly 0
.
third -- recasting malloc redundant , may lead problems. do cast malloc return value?
in c++
can(should) use built in operators new
, delete
.
also dont forget free()
allocated memory on heap.
Comments
Post a Comment