Pointer to 2D array. Why does this example work?
        Posted  
        
            by Louise
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Louise
        
        
        
        Published on 2010-06-15T00:18:56Z
        Indexed on 
            2010/06/15
            0:22 UTC
        
        
        Read the original article
        Hit count: 549
        
I have this code example, but I don't understand why changing the values in the array inside 
outputUsingArray() are changing the original array.
I would have expected changing the values of the array in outputUsingArray() would only be for a local copy of the array.
Why isn't that so?
However, this is the behaviour I would like, but I don't understand why it work.
#include <stdlib.h>
#include <stdio.h>
void outputUsingArray(int array[][4], int n_rows, int n_cols) {
  int i, j;
  printf("Output Using array\n");
  for (i = 0; i < n_rows; i++) {
    for (j = 0; j < n_cols; j++) {
      // Either can be used.
      //printf("%2d ", array[i][j] );
      printf("%2d ", *(*(array+i)+j));
    }
    printf("\n");
  }
  printf("\n");
  array[0][0] = 100;
  array[2][3] = 200;
}
void outputUsingPointer(int (*array)[4], int n_rows, int n_cols) {
  int i, j;
  printf("Output Using Pointer to Array i.e. int (*array)[4]\n");
  for (i = 0; i < n_rows; i++) {
    for (j = 0; j < n_cols; j++) {
      printf("%2d ", *(*(array+i) + j ));
    }
    printf("\n");
  }
  printf("\n");
}
int main() {
  int array[3][4] = { { 0, 1, 2, 3 },
              { 4, 5, 6, 7 },
              { 8, 9, 10, 11 } };
  outputUsingPointer((int (*)[4])array, 3, 4);
  outputUsingArray(array, 3, 4);
  printf("0,0: %i\n", array[0][0]);
  printf("2,3: %i\n", array[2][3]);
  return 0;
}
© Stack Overflow or respective owner