-1

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

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

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

char name[5][10];
strcpy(name[0],"hello");

Why first case not working?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Jayesh
  • 4,755
  • 9
  • 32
  • 62

2 Answers2

2

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 §6.3.2.1

[....] 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.

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Probably it will be interesting to mention about `strcpy` and how it works. Maybe then the OP will understand more clearly why it works with `strcpy` and why it does not work with its approach. :) – Michi Aug 22 '17 at 11:33
  • 2
    @Michi well, that would be too much (too broad). OP already claims to know why strcpy works but not direct assignment. – Sourav Ghosh Aug 22 '17 at 11:35
1

Because C does not allow to assign to an array. It's a limitation in the language.

Note that you can assign to a struct, even if it contains an array:

#include <stdio.h>
struct x
{
    char s[20];
};

int main(void)
{
    struct x x;
    x = (struct x){ "test" };
    puts(x.s);
}