int a[10];
int b[10];
a = b; // illegal
typedef struct {
int real;
int imag;
} complex;
complex c,d;
c = d; //legal
[I realize that
The first thing to understand is that arrays are not pointers. Read section 6 of the comp.lang.c FAQ. I'll wait.
...
Ok, done? No, go back and read the whole thing.
...
Great, thanks.
Generally speaking, arrays in C are second class citizens. There are array types, and array objects, and even array values, but arrays are almost always manipulated via pointers to their elements.
This requires a bit more work for the programmer (as you've seen, 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 can't be determined until execution time. Even if array assignment were permitted, an array of 10 int
s and an array of 20 int
s are of different and incompatible types. If you have a fixed-size array, as in the code in your question, it's common for only some of the elements to be currently relevant; you might have a 10-element array, but you're only currently using the first 5 elements. Processing such an array element-by-element makes it easier to process only the elements that are currently active (something you have to keep track of yourself).
For a struct, on the other hand, the number and types of the members are determined when you define the type. You can't traverse the members of a struct by advancing a pointer, as you would for an array, since the members are typically of different types. Arrays and structures are different things, and they have different sets of operations that make sense for them.
There are a couple of rules in the language that try to make it easier to do this, namely:
&
(address) operator;sizeof
; andint func(char s[]);
is adjusted to a pointer parameter: int func(char *s);
.(One could argue that these rules cause more confusion than they prevent, but that's the way the language is defined.)
Now I suppose the language could have been defined, or could be redefined, so that array assignment is permitted in cases where it makes sense:
int a[10];
int b[10];
/* ... */
a = b; /* Why not? */.
Perhaps such a change could even be made without breaking existing code. But that would require another special case for the array-to-pointer conversion rule. And it would only be useful in the case of fixed-size arrays like a
and b
, which though they're quite common in introductory programming exercises, are not as common in production code.