Why can´t we assign a new string to an char array, but to a pointer?

To understand what’s going on here, two language rules are important:

  • Arrays are not assignable.
  • An array can be converted to a pointer to its first element.

It’s also important to understand what a string literal like "Sunstroke" is. It’s a static array of constant characters, large enough to hold all the characters of a string with a terminator at the end. So in this case, it’s a const char[10] array, containing the nine characters followed by the zero-valued terminator. Being static, the array is stored somewhere in memory for the lifetime of the program.

char a[] = "Sunstroke";

This creates a local array, and initialises it by copying the characters from the string literal.

char *b = "Coldwave";

This creates a pointer, and initialises it to point to the literal itself. Note that this is dangerous: the literal is const, but the pointer isn’t, so you can write code that attempts to modify the literal, giving undefined behaviour. This conversion is deprecated (certainly in C++, I’m not sure about C), so the compiler should give you a warning. You have enabled all the compiler warnings you can, haven’t you?

a = "Coldwave";

This attempts to reassign the array, but fails because arrays aren’t assignable. There’s no particularly good reason why they aren’t; that’s just the way the languages evolved.

b = "Sunstroke";

This reassigns the pointer to point to a different literal. That’s fine (apart from the lack of const noted above).

If you need to manipulate strings, then:

  • in C you’ll need to carefully create arrays large enough for your needs, and use the library functions in <string.h> (or your own handcrafted code) to manipulate the characters in those arrays;
  • in C++, use the std::string class to handle memory management, assignment, etc. for you.

Leave a Comment