Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char array declaration and initialization in C

Tags:

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!

like image 228
Alexey Pimenov Avatar asked Feb 12 '11 12:02

Alexey Pimenov


People also ask

How are char arrays declared and initialized in C?

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.

What is character array How do you declare and initialize it?

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.

What is a char array in C?

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)

How do you initialize a char?

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.


1 Answers

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.

like image 139
Frédéric Hamidi Avatar answered Sep 19 '22 16:09

Frédéric Hamidi