C pointer notation compared to array notation: When passing to function
Solution 1:
When you declare a function parameter as an array, the compiler automatically ignores the array size (if any) and converts it to a pointer. That is, this declaration:
int foo(char p[123]);
is 100% equivalent to:
int foo(char *p);
In fact, this isn't about notation but about the actual type:
typedef char array_t[42];
int foo(array_t p); // still the same function
This has nothing to do with how you access p
within the function. Furthermore, the []
operator is not "array notation". []
is a pointer operator:
a[b]
is 100% equivalent to:
*(a + b)
Solution 2:
There is no real functional difference between the two notations. In C, when you pass an array variable to a function, it decays to a pointer regardless of the notation. However, in my opinion, the pointer notation is preferable. The problem with []
notation in function definitions is that, in my opinion, it is somewhat misleading:
void foo(int array[])
{
}
A ubiquitous mistake among novice C programmers is to assume that sizeof(array)
will give you the number of elements in the array multiplied by sizeof(int)
, like it would if array
were an array variable declared on the stack. But the reality is that array
has been decayed to a pointer, despite the misleading []
notation, and so sizeof(array)
is going to be sizeof(int*)
. array
is really just a pointer to the first element, or possibly a pointer to a single integer allocated anywhere.
For example, we could call foo
like this:
int x = 10;
foo(&x);
In which case the []
notation in the definition of foo
is kind of misleading.