james james - 2 months ago 7
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
B[2]
by:
&B[2]
or
B+2
.

But say I declared the 2-dimensional array
A[3][6]
how would I access a particular pointer in the array for
A[i][j]
using pointer arithmetic and not
&A[i][j]
?

Answer

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).

Comments