Jayesh Jayesh - 7 months ago 38
C Question

Assigning direct string to char array in C

In 2D array, assigning direct string to char array, getting an error.

char name[5][10];
name[0] = "hello";

But, using
, copy the string to char array working fine.

char name[5][10];

Why first case not working?

Answer Source

Because, an array type is not a modifiable lvalue, hence cannot be "assigned".

An assignment operator needs a modifiable lvalue as the LHS operand.

Related, quoting C11, chapter §6.5.16

An assignment operator shall have a modifiable lvalue as its left operand.

and, chapter §

[....] A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a constqualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a constqualified type.

In your case, for an array defined like

char name[5][10];

the element name[0] is of type char [10], that is, an array of 10 chars.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download