when I need to pass an array to a function, it seems all the following declarations of the function will work
void f(int arr[])
void f(int arr[4]) // is this one correct?
for this:
int a[]={1,2,3,4};
f(a);
But when I assign an array to another array, it fails
int a[]={1,2,3,4};
int b[4] = a; // error: array must be initialized with a brace-enclosed initializer
So why an array passed as an argument of a function is okay, but used on the rhs of simple assignment is wrong?
For understanding the difference, we need to understand two different contexts.
Tis equivalent to a pointer to typeT, and is equal to a pointer to the array’s first element.Tdoes not reduce to a pointer.What is object context?
In
a = b;,ais in object context. When you taken the address of a variable, it’s used in object context. Finally, when you usesizeofoperator on a variable, it’s used in object context. In all other cases, a variable is used in value context.Now that we have this knowledge, when we do:
It is exactly equivalent to
As you found out, we can omit the size (4 above) from the function declaration. This means that you can’t know the size of the “array” passed to
f(). Later, when you do:In the function call, the name
ais in value context, so it reduces to a pointer toint. This is good, becausefexpects a pointer to anint, so the function definition and use match. What is passed tof()is the pointer to the first element ofa(&a[0]).In the case of
The name
bis used in a object context, and does not reduce to a pointer. (Incidentally,ahere is in a value context, and reduces to a pointer.)Now,
int b[4];assigns storage worth of 4ints and gives the namebto it.awas also assigned similar storage. So, in effect, the above assignment means, “I want to make the storage location the same as the previous location”. This doesn’t make sense.If you want to copy the contents of
aintob, then you could do:Or, if you wanted a pointer
bthat pointed toa:Here,
ais in value context, and reduces to a pointer toint, so we can assignato anint *.Finally, when initializing an array, you can assign to it explicit values:
Here, a has 4 elements, initialized to 1, 2, 3, and 4. You could also do:
If there are fewer elements in the list than the number of elements in the array, then the rest of the values are taken to be 0:
sets
a[2]anda[3]to 0.