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?

2
  • An array is not the same as a pointer. Never has been. An this as been covered on Stack Overflow more times than I can count (integer overflow). Commented Jan 12, 2014 at 17:50
  • The C FAQ has a nice page on the answer. Commented Jan 12, 2014 at 17:50

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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";.
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");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.