I have been working through Stroustrup’s C++ programming language, and I am having difficulties with an early exersize. The task is to build a method rev that reverses a c style string. I think my logic is right, but I get an error when I try to modify the string. Can I not do this?
int strlen_(char* string)
{
int count = 0;
while (*string != '\0'){
count ++;
string ++;
}
return count;
}
void rev(char* string)
{
//length of the string is going to be useful
int len = strlen_(string);
//two counters, one going forward, one going back
int forwardIndex = 0;
int backwardIndex = len-1;
char temp;
while (forwardIndex < backwardIndex){
temp = string[forwardIndex];
string[forwardIndex] = string[backwardIndex]; //Exception Here
string[backwardIndex] = temp;
forwardIndex--;
backwardIndex--;
}
}
void main()
{
char* test = "test";
rev(test);
}
You can’t modify literal strings, and your reverse function modifies it’s string argument.
Test your reverse function by passing something like this instead:
This will make a copy of the literal string
"test"in an array that you can modify.Also, you’re decrementing both
forwardIndexandbackwardIndex: you should be incrementingforwardIndex:forwardIndex++. The idea is that the indices will meet in the middle.