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";
3
  • 2
    The "assignment below" is not an assignment. Commented Mar 18, 2015 at 15:32
  • You cannot assign to an array, use strcpy. Commented Mar 18, 2015 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". Commented Mar 18, 2015 at 15:41

2 Answers 2

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.

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

Comments

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"};

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.