I was curious about why this is not allowed in C:
char myarray[4];
myarray = "abc";
And this is allowed:
char myarray[4] = "abc";
I know that in the first case I should use strcpy:
char myarray[4];
strcpy(myarray, "abc");
But why declaration and later initialization is not allowed and declaration and simultaneous initialization is allowed? Does it relate to memory mapping of C programs?
Thanks!
That’s because your first code snippet is not performing initialization, but assignment:
And arrays are not directly assignable in C.
The name
myarrayactually resolves to the address of its first element (&myarray[0]), which is not an lvalue, and as such cannot be the target of an assignment.