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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With