Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character Array initialization

Tags:

c

string

I'm currently playing a bit with C and trying to understand strings. Can somebody please explain why this is working:

char test[] = "test";

And why the following does not?

char test[255];
test = "test";
like image 343
dropper Avatar asked Jul 06 '26 00:07

dropper


1 Answers

Because this is an initialization:

char test[] = "test";

and this is an assignment:

test = "test";

and you cannot assign arrays in C (and strings in C are just arrays).

Your best bet is to copy the string using strcpy() (or to be safe, strncpy()).

like image 85
Oliver Charlesworth Avatar answered Jul 08 '26 13:07

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!