arrays - Pointer to a pointer in C not working as expected -
i learning pointers in c. have 2d array of integers , i'm trying add elements in single row. 2d array name a
. know a
pointer array rows, pointers integer elements. want loop on entire array a
. so, declared pointer **pp
equal a
, since a
pointer pointer. program crashing @ run time.
int main(void){ int sum=0; int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; int **pp = null; int *p = null; (pp=a;pp<a+3;pp++){ (p=*pp;p<*pp+3;p++) sum += *p; printf("sum = %d\n", sum); sum = 0; } }
i know address of first object of 2d array a
. address of second object a+1
, on. matrix element i,j
example *(*(a+i)+j)
. in order words, if set pointer variable pp
(a+i)
, know i'm in i-th row. address of first integer element of i-th row *(a+i)
, why made p=*pp
. element (i,0)
should *p
same *(*(a+i)+0)
. so, why isn't code running should ?
following code works though needs cast :
int main(void){ int sum = 0; int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int *pp = (int*)a; (int = 0; < 3; ++i){ (int j = 0; j < 3; ++j){ sum += *pp; pp++; } printf("sum = %d\n", sum); sum = 0; } }
it little academic example because don't need pointers @ all. point is address of memory array begins. can cast first element pointer int. , following integers can reached doing pp++; moves pointer right sizeof(int). traverse multi dimentional array in linear way.