Recently, I was debugging one of my programs and found a mistake that I've constantly make, but it was not shown as a warning during compilation, so I've just assume everything was in place and was OK. I a bit confused on what's happening in the code below:
void foo(char b[2]);
char a[2] = {1, 2};
foo(a); // I always assumed that this would pass the entire array to be
// duplicate in stack, guess I was wrong all this while
// Instead the address of the array was passed
void foo(char b[2])
{
// Value of b[0], b[1]?
// Does this mean : 1) b[0] == &a[0]?
// or 2) b[0] == &a[0+2]?
// Compiler didn't complain, so I assume this is a valid syntax
}
When you pass an array as a parameter to a function it decays into a pointer, this is defined in the C standard in 6.7.1
:
On entry to the function the value of each argument expression shall be converted to the type of its corresponding parameter, as if by assignment to the parameter. Array expressions and function designators as arguments are converted to pointers before the call. A declaration of a parameter as “array of type” shall be adjusted to “pointer to type,”
This essentially means that in your function declaration it's equivalent to use
void foo(char b[2]);
or
void foo(char b[]);
or
void foo(char *b)
`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With