Time again for the usual spiel --
When an expression of array type appears in most contexts, its type is implicitly converted from "N-element array of T" to "pointer to T" and its value is set to point to the first element of the array. The exceptions to this rule are when the array expression is the operand of either the sizeof
or &
operators, or when the array is a string litereal being used as an initializer in a declaration.
So what does all that mean in the context of your code?
The type of the expression bar
is "6-element array of unsigned char" (unsigned char [6]
); in most cases, the type would be implicitly converted to "pointer to unsigned char" (unsigned char *
). However, when you call pass_char_ref
, you call it as
pass_char_ref(&bar);
The &
operator prevents the implicit conversion from taking place, and the type of the expression &bar
is "pointer to 6-element array of unsigned char" (unsigned char (*)[6]
), which obviously doesn't match the prototype
void pass_char_ref(unsigned char *foo) {...}
In this particular case, the right answer is to ditch the &
in the function call and call it as
pass_char_ref(bar);
Now for the second issue. In C, you cannot assign string values using the =
operator the way you can in C++ and other languages. In C, a string is an array of char with a terminating 0, and you cannot use =
to assign the contents of one array to another. You must use a library function like strcpy
, which expects parameters of type char *
:
void pass_char_ref(unsigned char *foo)
{
strcpy((char *)foo, "hello");
}
Here's a table of array expressions, their corresponding types, and any implicit conversions, assuming a 1-d array of type T (T a[N]
):
Expression Type Implicitly converted to
---------- ---- -----------------------
a T [N] T *
&a T (*)[N]
a[0] T
&a[0] T *
Note that the expressions a
, &a
, and &a[0]
all give the same value (the address of the first element in the array), but the types are all different.