Reputation: 31
I have a problem with my code below, I am trying to reverse a string, but I have run time error, anyone who can help me check it? The problem is:
eg:
INPUT: char *s = "This is my string"
OUTPUT: "string my is This"
#include <iostream>
using namespace std;
void reverse(char *str, int start, int end){
char tmp;
while(end > start){
tmp = str[end];
str[end] = str[start];
str[start] = tmp;
end--;
start++;
}
}
int main()
{
char *s = "This is my string";
int len = strlen(s);
int start = 0;
int end = len-1;
reverse(s, start, end);
printf("%s", s);
end = 0;
while( end < len){
if(s[end] == ' '||s[end] =='\0'){
while(s[start]==' ')
start++;
reverse(s,start,end-1);
start = end;
}
end++;
}
printf("%s", s);
cin.get();
}
Upvotes: 1
Views: 823
Reputation: 33655
You cannot modify this string:
char *s = "This is my string";
You've declared it incorrectly, it should be
const char* = "This is my string";
Normally these strings are allocated in a region of memory which you cannot write to. You should create another buffer to write the reversed string to.
Upvotes: 3