Friday, July 11, 2008

Pointer to 2D array

在网上看到讨论用指针读取2维数组的数据的问题,在comp.lang.c上找到了正解

______________________________________________________

int **ptr;

"ptr is a pointer to a pointer to int."

In the following, the offsets are in bytes (no pointer arithmetic) and sizeof(int) is assumed to be 4.

ptr[0][0] generates code like *((*p + (0 * 4)) + (0 * 4)) ptr[1][1] generates code like *((*p + (1 * 4)) + (1 * 4))

int (*ptr)[5];

"ptr is a pointer to an array of 5 int."

ptr[0][0] generates code like *((*p + (0 * 4)) + (0 * 4 * 5)) ptr[1][1] generates code like *((*p + (1 * 4)) + (1 * 4 * 5))

Where the 5 above is the number of array elements in the second dimension.

Quite different addresses!

int *ptr[5];

"ptr is an array of 5 pointers to int."

Note that the precedence of [] is higher than *.

No comments: