In some legacy code I have to maintain, & operators are put in front of arrays names whenever the arrays are to be passed as (void *) arguments
Here is a simple example :
char val = 42;
char tab[10];
memcpy(&tab, &val, 1);
It compiles with gcc or clang without errors or warnings. It also gives the expected result.
Is this syntax legal ?
Why does this works ?
Notes : I usually use one of the following syntax :
memcpy(tab, &val, 1);
memcpy(&tab[0], &val, 1);
Epilog :
As an additional test, I used a function taking a (char*) argument instead of (void*)
I get the following warning if I try to compile with clang :
warning: incompatible pointer types passing 'char (*)[10]' to parameter of type 'char *' [-Wincompatible-pointer-types]
Edit 1 : In the original example tab was given with a size of 1 element
I just changed the size to 10 for the sake of generality.
Edit 2 : As mentionned in the answers, memcpy takes (void*) and not (char*)
memcpy
's parameters are of type void*
, not char*
. Any argument of pointer type (excluding function pointers) is implicitly converted to void*
. This is a special-case rule that applies only to void*
.
Given the declaration
char tab[1];
either tab
or &tab
is valid as an argument to memcpy
. They evaluate to pointers of different types (char*
and char (*)[1]
), but both pointing to the same memory location; converting either to void*
yields the same value.
For a function that actually requires a char*
argument, only tab
is valid; &tab
is of the wrong type. (For a variadic function like printf
or scanf
, the compiler may not be able to detect the type mismatch.)
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