I am a little surprised by the following.
Example 1:
char s[100] = 'abcd'; // declare and initialize - WORKS
Example 2:
char s[100]; // declare s = 'hello'; // initalize - DOESN'T WORK ('lvalue required' error)
I’m wondering why the second approach doesn’t work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?
When initializing an array, C allows you to fill it with values. So
is basically the same as
but it doesn’t allow you to do the assignment since
sis an array and not a free pointer. The meaning ofis to assign the pointer value of
abcdtosbut you can’t changessince then nothing will be pointing to the array.This can and does work if
sis achar*– a pointer that can point to anything.If you want to copy the string simple use
strcpy.