pointer arithmetic with 2d arrays?

Quote:

>Hello...

>I'm trying to do pointer arithmetic with 2d arrays. Example:

>int arr[15][15];

>call_func(arr) = array initialization...;

>int call_func ( int arr[][15] )

>{

> arr = arr + 1; /* arr is now arr[1][0] */

Not exactly. Lets create a separate variable to avoid confusion (remove the

line above).

int (*arr2)[15] = arr;

After

arr2++; /* or ++arr2 or arr2 += 1 or arr2 = arr2 +1 */

then arr2 is now arr+1 or &arr[1].

*arr2 would be *(arr+1) or arr[1] or &arr[1][0].

**arr2 would be **(arr+1) or *arr[1] or arr[1][0]

Quote:

> printf("%d", **arr); /* prints data contained in

> arr[1][0] */

>}

>how would i use pointer arithmetic to access the nth element of

>arr[1]... like arr[1][4]? i've tried many different methods, but none

>work... thanks for any help.

The first thing to realise is that the [] notation is a form of pointer

arithmetic i.e. p[i] is defined as *(p + i). [] always takes a pointer and

an integer operand. So if you want arr[1][4] you can say just that with the

[] notation specifying the correct pointer arithmetic. Given the definition

of [] above this is equivalemtn to (*(arr+1))[4] or *(*(arr+1)+4). Since

arr2 is arr+1 that would be (*arr2)[4] or *(*arr2 + 4).

However that looks somewhat complex and it can be shown more clearly using

a separate pointers for the row and column. Consider this:

void call_func ( int arr[][15] )

{

int (*rowp)[15];

int *colp;

rowp = arr + 1; /* rowp now points to the second row */

colp = *rowp + 4; /* colp now points to the 5th column on the 2nd row */

printf("%d", *colp); /* prints data contained in arr[1][4] */

Note that colp is pointing to an element in a row i.e. an element of an

array of int so it has type pointer to int.

--

-----------------------------------------

-----------------------------------------