Originally Posted by
louis_mine
how do I move the pointer to another direction, for example: arr[2][10]
by just manipulating the pointer
Thanks
Suppose you have defined constants NUMROWS and NUMCOLS as the number of rows and number of columns, and you have this
Code:
int i_array[NUMROWS][NUMCOLS];
There are NUMROWS * NUMCOLS contiguous integers in the array, and the address of element i_array[x][y] is equal to this
Code:
&i_array[0][0] + NUMCOLS * x + y;
Note that you must always know the number of columns to access the individual elements.
Try this:
Code:
#include <stdio.h>
int main(void)
{
int i_array[2][3] = {{1, 2, 3} , {4, 5, 6}}; /* 2 rows, 3 columns */
int *i_point;
int j, k;
for (j = 0; j < 2; j++) {
for (k = 0; k < 3; k++) {
printf("i_array[%d][%d] = %d, ", j, k, i_array[j][k]);
printf("&i_array[%d][%d] = %p\n", j, k, &i_array[j][k]);
}
}
printf("\n\n");
/*
* for i_array[NumRows][NumCols] the address if element i_array[x][y] is
* given by this
*
* &i_array[x][y] is equal to &i_array[0][0] + (NumCols * x) + y
*
*
*/
i_point = &i_array[0][0];
printf("i_point = %p\n", i_point);
for (j = 0; j < 2; j++) {
for (k = 0; k < 3; k++) {
printf("*(i_point + 3 * %d + %d) = %d, ", j, k, *(i_point + 3*j + k));
printf(" (i_point + 3 * %d + %d) = %p\n", j, k, (i_point + 3*j + k));
}
}
return 0;
}
This arrangement of the elements is called "row-major" ordering, since the elements of a given row are contiguous in memory. Some other languages (FORTRAN for example) store array elements with "column-major" ordering.
Regards,
Dave