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!
Use {} Curly Braced List Notation to Initialize a char Array in C. A char array is mostly declared as a fixed-sized structure and often initialized immediately. Curly braced list notation is one of the available methods to initialize the char array with constant values.
Declaration of a char array is similar to the declaration of a regular array in java. “char[] array_name” or “char array_name[]” are the syntaxes to be followed for declaration. After declaration, the next thing we need to do is initialization. “array_name = new char[array_length]” is the syntax to be followed.
In C, an array of type char is used to represent a character string, the end of which is marked by a byte set to 0 (also known as a NUL character)
In C++, when you initialize character arrays, a trailing '\0' (zero of type char) is appended to the string initializer. You cannot initialize a character array with more initializers than there are array elements. In ISO C, space for the trailing '\0' can be omitted in this type of information.
That's because your first code snippet is not performing initialization, but assignment:
char myarray[4] = "abc"; // Initialization.
myarray = "abc"; // Assignment.
And arrays are not directly assignable in C.
The name myarray
actually 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With