When I want to pass an array by reference to a function I don't know what to choose.
void myFunction(int* data);
Is there a difference or a best coding way between those two cases:
myFunction(&data[0]);
Or
myFunction(data);
There is no difference. Arrays ("proper" arrays) automatically decay to pointers to their first element.
For example, lets say you have
int my_array[10];
then using plain my_array
will automatically decay to a pointer to its first element, which is &my_array[0]
.
It is this array-to-pointer decay that allows you to use both pointer arithmetic and array indexing for both arrays and pointers. For the array above my_array[i]
is exactly equal to *(my_array + i)
. This equivalence also exists for pointers:
int *my_pointer = my_array; // Make my_pointer point to the first element of my_array
Then my_pointer[i]
is also exactly equal to *(my_pointer + i)
.
For curiosity (and something you should never do in real programs), thanks to the commutative property of addition an expression such as *(my_array + i)
will also be equal to *(i + my_array)
which is then equal to i[my_array]
.