The first thing to understand is that arrays are not pointers. Read section 6 of the comp.lang.c FAQ . I'll wait.
...
Well done? No, go back and read it all.
...
Excellent thank you.
Generally speaking, arrays in C are second-class citizens. There are array types, array objects, and even array values, but arrays are almost always controlled by pointers to their elements.
It takes a little more work for the programmer (as you saw, you can't just assign arrays), but it also gives you more flexibility. Programs that deal with arrays usually need to deal with arrays of different sizes, even sizes that cannot be determined before runtime. Even if array assignment is allowed, an array of 10 int
and an array of 20 int
have different and incompatible types. If you have an array of a fixed size, as in the code in your question, it is common only for some of the elements that are currently relevant; you may have a 10 element array, but currently you are only using the first 5 elements. Processing such an element by element simplifies the processing of only those elements that are currently active (something that you must track yourself).
For a structure, on the other hand, the number and types of members are determined when determining the type. You cannot traverse the members of a structure by advancing a pointer, as with an array, since members usually have different types. Arrays and structures are two different things, and they have different sets of operations that make sense to them.
There are several rules in the language that simplify this, namely:
- In most, but not all contexts, an array expression is implicitly converted to a pointer to the first element of the array. The exception is:
- When an array expression is an operand of the
&
(address) operator, - When is the operand
sizeof
; and - When it is a string literal in the initializer, used to initialize the array object.)
- The declared array parameter, as in
int func(char s[]);
, configurable by pointer parameter: int func(char *s);
.
(It can be argued that these rules cause more confusion than they prevent, but how language is defined.)
Now I assume that the language could be defined or can be redefined, so that the assignment of the array is allowed in cases where this makes sense:
int a[10]; int b[10]; a = b; .
Perhaps such a change could even be made without breaking existing code. But this will require another special case for the rule of converting an array to a pointer. And this would only be useful in the case of fixed-size arrays, such as a
and b
, which, although they are quite common in introductory programming exercises, are not so common in production code.