0
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?

dmckee --- ex-moderator kitten
  • 98,632
  • 24
  • 142
  • 234
dfg
  • 777
  • 1
  • 8
  • 24

3 Answers3

2

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.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96
0

The second piece of code is invalid. Why?

Because arrays names are non-modifiable l-values.

Isn't string2 a char* like string?

No. string2 is an array of 2 chars 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.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • The `=` operator does not copy data from one string to another. The problem here has nothing to do with the number of characters involved. It would still be an error if it read `char string2 [2] = "abc"; string2 = "a";`. – dmckee --- ex-moderator kitten Jan 12 '14 at 17:54
0

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");
sujin
  • 2,813
  • 2
  • 21
  • 33