Cannot reverse simple std::string

I know that I could print the following string simply by for cycle, but I want to know why it does not work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <string>
#include <iostream>

int main(int argc, char** argv)
{
    if(argc == 2)
    {
        std::string textorig(argv[1]);
        std::string textreversed;
        for(int i = textorig.length()-1; i >= 0; i--)
        {
            textreversed[i] = textorig[i];
        }
        std::cout << textreversed << std::endl;
    }
    return 0;
}


When I compile this with "g++ main.cpp" and run by "./a.out hello", it prints nothing except new line.
P.S. I am sorry for my bad english.
Do you realize that textreversed is an empty string and has no memory allocated to it? Trying to access elements of that empty string produces at best undefined behavior.

Also even if there were memory allocated to that string do you realize that your "reverse" method is incorrect since you are trying to place the character in the same location as the original string?

Perhaps something more like: textreversed += textorig[i];.


Should not std:string dynamically allocate and resize its own memory?
Last edited on
Not in this case. You're trying to access single elements that don't exist, not the string itself.

Topic archived. No new replies allowed.