tags:

views:

99

answers:

3

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;
}
+4  A: 

passing int[] is really passing the pointer to the first element of the array.
passing int* is passing the pointer to the first element of the array as well.

They're identical.

Since they're both pointing towards the same part of memory, changing one will change the other one.

ItzWarty
and it works since array is a pointer to int[4] so it has a fixed size the compiler knows about so it can do index calculations
Spudd86
+1  A: 

Arrays in C/C++ are not passed by value. i.e. there is NO copying involved when you pass an array as a parameter. i.e. array is just a name that references the passed array.

AraK
A: 

Arrays in C/C++ are really just pointers (with the math done for you). Unless you explicitly make a copy of the contents of the array, passing an array is only passing a pointer to the first element.

So when you modify the array based on that base pointer, you're modifying the original array contents.

Rob Parker
Arrays in C and C++ are not pointers. They *decay* into pointers in *some* contexts, but they are not the same.
jamesdlin