I thought I understood c and pointers but was just debugging someone elses code that I thought should not work but did. As a (crude) example....
void clear_buffer(char* buff, int len)
{
while(len)
{
*buff++ = ' ';
len--;
}
}
main()
{
char buffer[10];
clear_buffer(&buffer,10); // 1. what I found, it still works...
clear_buffer(buffer,10); // 2. what I would have wrote
}
What suprised me was that both calls above do work exactly the same way. The first one gives a compiler warning (incompatible pointer types) but it still builds and runs correctly. So my question is: is this the expected behaviour in C or is it just the compiler I am using being clever and fixing a bug? fwiw, this is using the microchip xc16 compiler.
This call
is incorrect and the compiler shall issue an error message.
The type of the expression
&buffer
ischar ( * )[10]
while the type of the corresponding function parameter ischar *
and there is no implicit conversion from one type to another.The program works as expected because the values of the expressions
&buffer
andbuffer
are the same: it is the address of the extent of memory occupied by the array though types of the expressions are different.Consider another example. Here is a demonstrative program
The program output is
as you can see the program outputs equal addresses though the types of the expressions
&a
and&a.x
are different.The same takes place in your program. The address of a whole array equal to the address of its first element though the types of the whole array and its element are different.
In fact in your function you are reinterpreting the pointer to the whole array of the type
char ( * )[10]
as a pointer to the first array element of the typechar *
.