-3

I use char array/pointer for in-place string reversal algo. Why the (1) gives segmentation fault and (2) works perfectly?

#include <iostream>
#include <cstring>
using namespace std;

//In-place string reversal
void ip_reverse(char* cstr)
{
    int len = strlen(cstr);
    int hlen = len/2;
    char ctmp;
    for(int i=0; i<hlen; i++)
    {
        ctmp = cstr[i];
        cstr[i] = cstr[(len-1)-i];
        cstr[(len-1)-i] = ctmp;
    }
}

int main()
{
   //char* cstr = "Kaboom";         //(1)This gives "Segmentation fault"! 
   char cstr[] = "Kaboom";          //(2)This works!

   cout << "Original string => " << cstr << endl;
   ip_reverse(cstr);
   cout << "Reversed string => " << cstr << endl;

   return 0;
}
deepdive
  • 9,720
  • 3
  • 30
  • 38

1 Answers1

4
char* cstr = "Kaboom";

In this case, the string literal "Kaboom" has array type. It gets converted to a pointer to the first character in the string literal and that pointer is stored in cstr. String literals, however, cannot be modified. In fact, you should have seen at least a warning for the above line. It should instead be a const char*.

char cstr[] = "Kaboom";

This is actually a special case of array initialisation. When you initialise an array with a string literal, it copies each element of the string literal to your array object. So then you have your own modifiable copy of the string.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324