0

I need to create a structure whose member is an character array like below:

struct Person{
    char name [100];

};

Why the below results in a incompatible types error? And how to fix it?

struct Person john;
john.name = "John"; 

what is the difference between the assignment above and bellow, which works well:

char str[100] = "this is a string";
PMH
  • 43
  • 5
  • 2
    The "assignment below" is *not* an assignment. – Kerrek SB Mar 18 '15 at 15:32
  • You cannot assign to an array, use `strcpy`. –  Mar 18 '15 at 15:34
  • It may help if you think that C has no strings. It does have string literals, which can be used in a few different ways, and it has standard library functions for manipulating byte sequences where 0-byte marks the end, AKA "strings". But if you are used to strings of almost any other language, these are not something you would call "strings". – hyde Mar 18 '15 at 15:41

2 Answers2

1

john.name = "John"; is an assignment (which is not possible in this case) while

char str[100] = "this is a string";  

is definition with initialization.

john.name = "John"; is an invalid statement in C because an array can't be a left operand of = operator. You need strcpy or strncpy to copy a string.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

C doesn't allow you to use the assignment operator with arrays. There is a special provision that allows you to initialize arrays with string literals:

struct Person john = {"John"};