c - How can I iterate a 2 dimensional array via pointers? -


i have 20x20 matrix. want extract chunks of data matrix. have

int thematrix[20][20] = {};//full code initializes #'s int *thematrixpointer = &thematrix; 

but compiler warning saying

warning: initialization incompatible pointer type

i went ahead , ran code , looks moving across matrix left right. @ least in short run. implementation:

//left right pointer; while(thematrixpointer) {     int 1 = 0;     int 2 = 0;     int 3 = 0;     int 4 = 0;     double currentproduct = 0;     //int stop = 0;     for(int = 0; < depth; i++)     {         /*if(!thematrixpointer)         {             stop = 1;             break;         }*/         int currentvalue = *thematrixpointer++;         printf("%d\n",currentvalue);         if(i == 0)         {             1 = currentvalue;         }         else if (i == 1)         {             2 = currentvalue;         }         else if (i == 2)         {             3 = currentvalue;         }         else if (i == 3)         {             4 = currentvalue;         }     }     /*if(stop)         break;*/     currentproduct = 1 * (double)two * 3 * four;     printf("product: %f\n",currentproduct);     startpoint++;     thematrixpointer = startpoint; } 

...breaks on time data garbage (big ints not in matrix). so, how can iterate matrix pointer?

firstly, reason warning because &thematrix of type int(*)[20][20], whereas thematrixpointer of type int *. want this:

int *thematrixpointer = &thematrix[0][0]; 

secondly, reason getting garbage because you're going past end of array. while (thematrixpointer) iterate until thematrixpointer == 0. remember thematrixpointer an address. won't 0 until you've iterated on entire address space , wrapped round!

you best off doing this:

int i, j; (i = 0; < 20; i++) {     (j = 0; j < 20; j++)     {         // matrixpointer[i][j] current element     } } 

Comments