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;
}