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.
std::reversedoesn't mean you shouldn't usestd::swap. Anyway, same underlying problem as stackoverflow.com/questions/24874073/…<string.h>is deprecated in C++. Pointing achar *to a string literal is also deprecated in C++ and should produce a compiler warning. In C++11, it is outright illegal.