pointers and multidimensional arrays

How would you declare a pointer variable pz that can point to a two-dimensional array such as zippo? Such a pointer could be used, for example, in writing a function to deal with zippo-like arrays. Will the type pointer-to-int suffice? No. That type is compatible with zippo[0], which points to a single int. But zippo is the address of its first element, which is an array of two ints. Hence, pz must point to an array of two ints, not to a single int. Here is what you can do:


int (* pz)[2];  // pz points to an array of 2 ints


This statement says that pz is a pointer to an array of two ints. Why the parentheses? Well, [ ] has a higher precedence than *. Therefore, with a declaration such as


int * pax[2];


you apply the brackets first, making pax an array of two somethings. Next, you apply the *, making pax an array of two pointers. Finally, use the int, making pax an array of two pointers to int. This declaration creates two pointers to singleints, but the original version uses parentheses to apply the * first, creating one pointer to an array of two ints. 



#include <stdio.h>

int main(void)
{
  char board[3][3] = {
                       {'1','2','3'},
                       {'4','5','6'},
                       {'7','8','9'}
                     };

  printf("address of board        : %p\n", board);
  printf("address of board[0][0]  : %p\n", &board[0][0]);
  printf("but what is in board[0] : %p\n", board[0]);
  return 0;
}
address of board        : 9a377
     address of board[0][0]  : 9a377
     but what is in board[0] : 9a377

No comments:

Post a Comment