C++使用堆栈弹出操作赋值字符值给char*

3

我正在尝试使用栈来反转一个char*。

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

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

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

在第二个 while 循环中,我不确定如何将栈顶的每个字符分配给 char* str。

1
你不应该只是反向迭代它并将其复制到新缓冲区中吗? - user3285991
2个回答

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();
    }
    

1
谢谢你提醒我"apple"是一个const char[]。 - coffeefirst

2
您也可以迭代指向char[]的指针,如果您愿意。
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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接