Search code examples
stringpointersconstantsc-stringsliterals

String (constants) Literals pointer


I'm relatively new to C++ and I searched for an answer to my question, however I got more confused. As I understand, string literals must be pointed by "const" pointers, since are considered to be readable only. I also understand the pointer itself is not constant (and could be changed), but actually it is pointing to a string constant.I also understand that the string itself cannot be modified. So in this example:

const char* cstr="string";
*cstr = 'a';

I get an error: "assignment of read-only location." Now, if I define my C-string as following, and define a pointer to it, I'll be able to change the string:

char str[7]="string";
char* cstr = str;
*cstr = 'a';
cout << cstr <<endl;

the string will be modified (output --> a), means the first element of the string is changes. My two questions are: 1- why in the second example I am able to modify the C-string but in the first case I cannot make any changes to the string? 2- In both cases I am using pointers, but in the first case I should Use constant char pointer?


Solution

  • When you use the syntax

    const char* cstr="string";
    

    C++ defines:

    • An array of 7 character in the read-only section of memory, with the contents string\0 in it.
    • pointer on the stack (or in the writable global section of memory), with the address of that array.

    However, when you use the syntax:

    char str[7]="string";
    

    C++ defines:

    • An array of 7 character on the stack (or in the writable global section of memory), with the contents "string\0" in it.

    In the first case, the actual values are in read-only memory, so you can't change them. In the second case, they are in writable memory (stack or global).

    C++ tries to enforce this semantic, so if the definition is read-only memory, you should use a const pointer.

    Note that not all architectures have read-only memory, but because most of them do, and C++ might want to use the read-only memory feature (for better correctness), then C++ programmers should assume (for the purpose of pointer types) that constants are going to be placed in read-only memory.