3

I am trying to reverse a char* by using a stack.

stack<char> scrabble;
char* str = "apple";

while(*str)
{
    scrabble.push(*str);
    str++;
    count++;
}

while(!scrabble.empty())
{
     // *str = scrabble.top();
     // str++;
     scrabble.pop();
}

In the second While-loop, I'm not sure how to assign each char from the stack's top to the char* str.

coffeefirst
  • 125
  • 2
  • 11
  • 1
    Shouldn't you just iterate over it backwards and copy it into a new buffer? –  Nov 05 '15 at 05:34

2 Answers2

7
  1. When you have a string defined using

    char* str = "apple";
    

    you are not supposed to change the value of the string. Changing such a string causes undefined behavior. Instead, use:

    char str[] = "apple";
    
  2. In the while loops, use an index to access the array instead of incrementing str.

    int i = 0;
    while(str[i])
    {
        scrabble.push(str[i]);
        i++;
        count++;
    }
    
    i = 0;
    while(!scrabble.empty())
    {
       str[i] = scrabble.top();
       i++;
       scrabble.pop();
    }
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

You can also iterate a pointer to the char[] if you'd like

char str[] = "apple";

char* str_p = str;
int count = 0;

while(*str_p)
{
    scrabble.push(*str_p);
    str_p++;
    count++;
}

// Set str_p back to the beginning of the allocated char[]
str_p = str;

while(!scrabble.empty())
{
     *str_p = scrabble.top();
     str_p++;
     scrabble.pop();
}
jsherman256
  • 100
  • 5