c ++将char值(通过使用堆栈弹出)分配给char*

cof*_*rst 2 c++ char

我试图通过使用堆栈来反转char*.

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

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

while(!scrabble.empty())
{
     // *str = scrabble.top();
     // str++;
     scrabble.pop();
}
Run Code Online (Sandbox Code Playgroud)

在第二个While循环中,我不确定如何将每个char从栈顶部分配给char*str.

R S*_*ahu 6

  1. 当您使用时定义了字符串

    char* str = "apple";
    
    Run Code Online (Sandbox Code Playgroud)

    你不应该改变字符串的值.更改此类字符串会导致未定义的行为.相反,使用:

    char str[] = "apple";
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在while循环中,使用索引来访问数组而不是递增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();
    }
    
    Run Code Online (Sandbox Code Playgroud)