c++将char值(通过使用栈pop)分配给char*
c++ assign char values (by using stack pop) to char*
我正试图通过使用堆栈来反转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.
-
当您使用定义字符串时
char* str = "apple";
您不应该更改字符串的值。更改这样的字符串会导致未定义的行为。相反,使用:
char str[] = "apple";
-
在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(); }
如果您想要,还可以迭代指向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();
}