Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is literal string assignment in C not possible for array with specified length? [duplicate]

Possible Duplicate:
What is the difference between char s[] and char *s in C?
Do these statements about pointers have the same effect?

All this time I thought that whenever I need to copy a string(either literal or in a variable) I need to use strcpy(). However I recently found out this:

char a[]="test";

and this

char *a="test";

From what I understand the second type is unsafe and will print garbage in some cases. Is that correct? What made me even more curious is why the following doesn't work:

char a[5];
a="test";

or this

char a[];
a="test";

but this works however

char *a;
a="test";

I would be greatful if someone could clear up things a bit.

like image 973
Pithikos Avatar asked Nov 07 '11 17:11

Pithikos


1 Answers

char a[]="test";

This declares and initializes an array of size 5 with the contents of "test".

char *a="test";

This declares and initializes a pointer to the literal "test". Attempting to modify a literal through a is undefined behavior (and probably results in the garbage you are seeing). It's not unsafe, it just can't be modified since literals are immutable.

char a[5]; a="test";

This fails even when both a and "test" have the exact same type, just as any other attempt to copy arrays thorugh assignment.

char a[]; a="test";

This declares an array of unknown size. The declaration should be completed before being used.

char *a; a="test";

This works just fine since "test" decays to a pointer to the literal's first element. Attempting to modify its contents is still undefined behavior.

like image 58
K-ballo Avatar answered Oct 05 '22 07:10

K-ballo