chefcurry7
chefcurry7

Reputation: 5251

Multidimensional array and pointer addressing

#include <stdio.h>
int main(void)
{
  int x[2][3] =
  {
    {4, 5, 2},
    {7, 6, 9}
  };
  int (*p)[3] = &x[1];
  int (*q)[3] = x;
  printf("%d %d %d\n", (*p)[0], (*p)[1], (*p)[2]);  //7, 6, 9
  printf("%d %d\n", *q[0], *q[1]);  // 4, 7
  return 0;
}

x[0] ----> [4, 5, 2].

x[1] ----> [7, 6, 9]

so if p=X[1], p[0]=7, p[1]=6 and p[2]=9, so the first printf is understandable.

For the second printf, x will be equal to the address first element of the array. If *q[0] is 4, why is *q[1] 7, shouldn't it be 5? It skips a row.


Actual output from link:

7 6 9
4 7

Upvotes: 1

Views: 56

Answers (4)

Lundin
Lundin

Reputation: 215255

It's an operator precedence issue. [] has higher priority than unary *. If [] is applied to an array pointer, it will perform pointer arithmetic by the same rules as for regular pointers.

For any pointer type, ptr[i] equals *(ptr + i), and ptr+i means "give me the address of ptr plus i*sizeof(*ptr) bytes.

So in your case q[1] means "give me the address of q + 1*sizeof(*q), where the contents of q is an array of 3 integers. So you end up pointing at the beginning of the 2nd array.

Upvotes: 0

ameyCU
ameyCU

Reputation: 16607

Output you get is valid .

*q[1] is equivalent to q[1][0] . And therefore , value at that index is 7 which you get as output .

To get 5 you can write like this q[0][1] or the other way to represent (*q)[1] .

Upvotes: 0

Constantin
Constantin

Reputation: 8961

Compare these two lines:

printf("%d %d %d\n", (*p)[0], (*p)[1], (*p)[2]);  //7, 6, 9
printf("%d %d\n", *q[0], *q[1]);  // 4, 7

In the first line you have dereferenced the pointer first and then accessing the index - in your second line you're missing the parenthesis. Changing it to:

  printf("%d %d %d\n", (*p)[0], (*p)[1], (*p)[2]);  // 7, 6, 9
  printf("%d %d %d\n", (*q)[0], (*q)[1]);  // 4, 5

Will output the values as you expect.

Upvotes: 1

RajSharma
RajSharma

Reputation: 1971

it is pointing to the second array in x.

If you want to get all elements of first row you can use something like this.

#include <stdio.h>
int main(void)
{
int x[2][3] =
{
{4, 5, 2},
{7, 6, 9}
};
int (*p)[3] = &x[1];
int (*q)[3] = x;
printf("%d %d %d\n", (*p)[0], (*p)[1], (*p)[2]);  //4, 5, 2
printf("%d %d %d\n", *q[0], q[0][1],q[0][2]);  // 4, 5,2
return 0;
}

Upvotes: 0

Related Questions