0

I am trying to reverse the characters for each command line argument.

This is the only code inside my main method:

 for(int z = 1; z < argc; z++) //Loop through every argument
    {
        string arg = argv[z]; //Grab the argument
        string rebuildString; //Create a string to build the result
        for(int i = arg.size()-1; i >= 0; i--) //Loop through characters backwards 
        {
            char c = arg[i];
            rebuildString += c; 
        }

        char *rebuildChars; //So since argv is an array of pointers, I create a pointer here.
        *rebuildChars = rebuildString.c_str(); //Assign the value of the pointer
        argv[z] = rebuildChars; //Assign the current argument to the new value.
    }

    for(int x = 1; x < argc; x++)
    {
        cout << argv[x];
    }

Something is going wrong with my pointers and I am getting some incompatible type errors. Can anyone point out what's going wrong?

  • What do the error messages tell you - they are usually quite descriptive – UnholySheep Mar 28 '19 at 19:53
  • What is `rebuildChars`? What is `*rebuildChars`? What does `rebuildString.c_str()` return? – Some programmer dude Mar 28 '19 at 19:59
  • Even more problematic, what happens with variables that go out of scope? For example a variable that is defined inside a loop, what happens when that loop iterates? What happens with pointers to data that the variable contain? You might want to study more about scoping and (more importantly) life-time of variables and objects. – Some programmer dude Mar 28 '19 at 20:00
  • All in all, it seems you could need [a good book or two](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to read. – Some programmer dude Mar 28 '19 at 20:02
  • `arg.size()-1` does evil things if the string is blank (subtraction from 0 in `unsigned` arithmetic). That's not the immediate issue here though; that's a *dangling pointer*. – Bathsheba Mar 28 '19 at 20:46

2 Answers2

0

The first thing that jumped out at me was that you assigning a pointer to a dereferenced char*.

    char *rebuildChars; //This is fine.
    *rebuildChars = rebuildString.c_str(); //ERROR! .c_str returns a char * !
    argv[z] = rebuildChars;

note the declaration of string.c_str() is const char* c_str() const noexcept; (C++11)

Instead try

    char *rebuildChars; //This is fine.
    rebuildChars = rebuildString.c_str(); //Here we assign a char * to a char *
    argv[z] = rebuildChars;

See THIS reference on TutorialsPoint.

armitus
  • 712
  • 5
  • 20
0

The problem is that when rebuildString goes out of scope, it is destroyed, and the pointer previously returned by rebuildString.c_str() becomes dangling (pointing at freed storage). So when you later try to print with it, you get undefined behavior.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226