0

I understand char* pString is read only, therefor pString[0]='A' will give a Segmentation fault, but why does pString2[0]='A' work in below code:

    char* pString  = "abcdefg";
    char tmpStr[80];
    strcpy(tmpStr, pString);
    char* pString2  = tmpStr;

    //pString[0] = 'A'; // gives segmentation error since string literal is read-only.
    pString2[0] = 'A'; // why this one works? 
    
user97662
  • 942
  • 1
  • 10
  • 29
  • `pString2` is pointing to the first element of the (non-constant) array `tmpStr`. You can modify the contents of `tmpStr` as much as you'd like, using the array directly or through a pointer like `pString2`. – Some programmer dude Dec 02 '21 at 14:42

2 Answers2

2

pString2 is not pointing to a string literal. It's pointing to the first element of a char array, and that array is not const, so writing to it is allowed.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

In this declaration

char* pString  = "abcdefg";

the string literal is the record "abcdefg" not the declared pointer.

The string literal in C has the type char[8]. Though in the type there is absent the qualifier const nevertheless you may not change a string literal. Any attempt to change a string literal results in undefined behavior.

In C++ opposite to C string literals have types of constant character arrays.

As for the declared pointer then it points to the first element of the string literal.

In this code snippet

char tmpStr[80];
strcpy(tmpStr, pString);

there is declared character array tmpStr. You may change the array.

In this statement

strcpy(tmpStr, pString);

elements of the string literal are copied in the character array.

And in the declaration below the declared pointer point to the first element of the array.

char* pString2  = tmpStr;

pString2[0] = 'A';

So you may change the array. You could use even the pointer pString instead of pString2 like

pString  = tmpStr;

pString[0] = 'A';

Pay attention to that you may initialize a character array with a string literal. So you could write for example

char tmpStr[] = "abcdefg";
*tmpStr = 'A';

or

tmpStr[0] = 'A';
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335