james james - 1 year ago 71
C Question

How to get the pointer address of A[i][j] using pointer arithmetic?

If I declare an array in C:

int B[4];
then I can get the pointer to address of

But say I declared the 2-dimensional array
how would I access a particular pointer in the array for
using pointer arithmetic and not

Answer Source

Answer by an example:

int A[3][6];
int i = 2;
int j = 4;
int* p = A[i]+j;

Of course, since any array is a consecutive piece of memory (consisting of 18 int elements in the example above), you can also cast it into a simple pointer, and then refer to whichever element you want.

For example:

int* p = (int*)A+i*6+j;

You can compute the exact number of columns (6 in the example above), using any of the following:

  • sizeof(*A)/sizeof(**A)
  • sizeof(A[0])/sizeof(A[0][0])
  • sizeof(A[x])/sizeof(A[y][z]) // x,y,z are any integer constants or variables

But you can do so safely only within the array's scope of declaration (function if it's a local variable, or file if it's a global variable).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download