I wrote the following code to reverse the string without using <algorithm> reverse
. I wrote:
#include <string.h>
#include <iostream>
using namespace std;
void reverse(char *str){
int sizeStr=strlen(str);
int firstChar,lastChar,temp;
for(lastChar = (sizeStr - 1),firstChar = 0 ; lastChar>firstChar ; lastChar--, firstChar++){
temp = str[firstChar];
str[firstChar]=str[lastChar];
str[lastChar] = temp;
}
}
int main() {
char *str;
str = "myname";
reverse(str);
cout << str << endl;
return 0;
}
I am getting segfault at str[firstChar]=str[lastChar];
. Please help me figure out my mistake.
NOTE: I declared char str[] = "myname"
and worked perfectly. But as per your all explanations got to learn differences for *str
and str[]
. Thanks a lot. Goes a long way in helping a new programmer.