Line offset with C ++ pointers

Possible duplicate:
Why does a segmentation error occur when writing to a string?

I want to write a simple C ++ function that changes string / char[] only with pointer arithmetic. I understand the concept and have already typed the code.

I have the following .cpp file:

 #include <iostream> using std::cout; using std::endl; void reverse(char* target) //Requirements specify to have this argument { cout << "Before :" << target << endl; // Print out the word to be reversed if(strlen(target) > 1) // Check incase no word or 1 letter word is placed { char* firstChar = &target[0]; // First Char of char array char* lastChar = &target[strlen(target) - 1]; //Last Char of char array char temp; // Temp char to swap while(firstChar < lastChar) // File the first char position is below the last char position { temp = *firstChar; // Temp gets the firstChar *firstChar = *lastChar; // firstChar now gets lastChar *lastChar = temp; // lastChar now gets temp (firstChar) firstChar++; // Move position of firstChar up one lastChar--; // Move position of lastChar down one and repeat loop } } cout << "After :" << target << endl; // Print out end result. } void main() { reverse("Test"); //Expect output to be 'tseT' } 

I went into the debugger several times, but each time it breaks around the line temp = *firstChar in a while loop. It freezes here and causes the program to stop working and cannot end. Is there something that I'm just browsing or is there something deeper as to why I cannot do it this way.

EDIT: There is another condition, but I removed it for the sake of brevity. This was after the if , and it just suggested that the word was 1 char or the word was not placed.

+6
source share
2 answers

The problem is not the reverse function, but the calling code.

 reverse("Test"); 

String literals are read-only, attempting to change one leads to undefined behavior. Pay attention to compiler warnings (or raise the warning level if you do not receive them). The line above should generate a failover conversion warning from const char * to char * .

To fix the code:

 int main() // <-- note the return type, int NOT void! { char str[] = "Test"; reverse( str ); } 
+8
source

This code will change it twice. Divide the cycle into two.

0
source

All Articles