char *string = "a";
string = "abc";
The above piece of code is valid.
char string2 [2] = "a";
string2 = "abc";
The second piece of code is invalid. Why? Isn't string2
a char*
like string
? How can the same type have different properties?
char *string = "a";
string = "abc";
The above piece of code is valid.
char string2 [2] = "a";
string2 = "abc";
The second piece of code is invalid. Why? Isn't string2
a char*
like string
? How can the same type have different properties?
string
is a pointer to a char
. string2
is an array of char
elements. Those two are different types.
In your second example, you are trying to assign a pointer to an array (string literals evaluate to pointers.) This makes no sense and isn't possible. It's really no different from:
int numbers[2];
int num;
numbers = # // How's that supposed to work?
People get a bit confused by this, because you can use the index operator []
on pointers, and the name of an array evaluates to a pointer to its first element. That doesn't mean that pointers are arrays, or vice versa. That's just some syntactic sugar to make access to the pointed to or contained data easier.
The second piece of code is invalid. Why?
Because arrays names are non-modifiable l-values.
Isn't
string2
achar*
likestring
?
No. string2
is an array of 2
char
s while string
is a pointer to char
.
How can the same type have different properties?
Do remember, pointers are not arrays. string
and string2
are of different type.
In your second code you trying to assign new string to array.
In C arrays are not directly assignable. You can use strcpy
char string2 [2] = "a";
strcpy(string2, "ab");