-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?

7
  • 3
    There are tons of Questions like this on SO. Commented Aug 22, 2017 at 11:27
  • 1
    Can we please have a better dupe? That is too much inclined to C++. Commented Aug 22, 2017 at 11:32
  • 3
    Thats not a DUP Commented Aug 22, 2017 at 11:34
  • @Michi indeed, but now that it's closed and I'm thinking about it, there must be one ... Commented Aug 22, 2017 at 11:36
  • hopefully fixed the dupe link to something suitable Commented Aug 22, 2017 at 11:39

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 well, that would be too much (too broad). OP already claims to know why strcpy works but not direct assignment.
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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.