Why does the second method of assigning a string
to char name2[]
not work? It causes a compilation error saying "Array type 'char[20]' is not assignable".
There is no "second method" presented. This ...
char name[20] = "Alex";
... does not demonstrate an assignment, but rather an initialization. The =
within is not functioning as the assignment operator, but rather as part of the syntax for specifying the initial value that name
will take. And yes, this is a common source of confusion for newcomers to C.
On the other side, it is not possible to assign to whole arrays in C (this also is a common source of confusion for newcomers). This is the reason for the compilation error. You can copy the contents of one array into another with, for example, strcpy()
or memcpy()
, but there are almost no operators that accept arrays as operands. C arrays have more surprises to offer you, too, but I won't spoil them.
Once you understand C's idiosyncratic treatment of arrays, I think you'll see that it's internally consistent. Until then, however, you would do well to be alert whenever you see or use an array.