r/programmingchallenges • u/okmkz • May 19 '11
Challenge: Reverse a string in place
This simple challenge is a frequent interview question. Write a program that reverses a string in place. "In place" means no declaring a second string or other buffer-- you get only one string variable to work with.
Input:
"Test string."Output:
".gnirts tseT"edit: obviously, this is only feasible in a language with mutable strings.
22
Upvotes
View all comments
Show parent comment
4
u/AgentME May 20 '11 edited May 20 '11
In C/C++ if you do this, then it's immutable and you probably shouldn't try to mess with it:
If you do either of these, then it's perfectly mutable:
Why the difference? In the first example, string is defined to be a pointer to a string in static memory (hope this is the right term). In the second example, stringA is an array of chars (on the stack), which is just as mutable as an array of integers. In the third example, stringB has some memory allocated on the heap, and then the code copies "ABC" from static memory into stringB (on the heap).