In C
, an array variable decays into a pointer to the memory address that contains the first element of the array, when it is passed as a parameter to a function. That is joined to the fact that all it's elements are placed in contigous memory. So C
only needs to save the first position of the array (no matter how many dimensions it has) and will then be able to calculate, based on the indexes, what offset of the pointed memory it should access.
So, on your particular piece of code variable a
points to the first element, which is a[0][0]
. So, basically doing this:
change_array(&a[0]);
Is roughly (but not exactly) the same as doing:
change_array(a);
Now, knowing how arrays are passed in C, you should be able to deduce that, indeed, two dimensional arrays, when passed as parameters, actually contain on the access to their first coordinate a pointer to where the first element of the second coordinate is. So, when you do array[0]
you're passing a pointer to the first element of the array under the first coordinate. and then when you do *(array[0])
you're actually accessing the first element of the second coordinate.
Here it is also important to add then that; since array variables decay into pointers, then all arrays in C are passed by reference, because you are passing a pointer. So all function calls that modify an array passed to them will do actual modifications.
Knowing this, then your function should be:
void change_array(int *array)
{
array[0] = -1;
array[1] = -1;
}
And then you can perform a call such as:
change_array(a[0]);
In order to modify the elements of the first array of a
.
Now, as good practice in C
, and in order to avoid segmentation faults, one would pass to the function along with the pointer, an integer saying the size of the array:
void change_array(int *array, int size);
And then always perform the access checking this bound.