繁体   English   中英

c ++将char值(通过使用堆栈弹出)分配给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从栈顶部分配给char * str。

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

     char* str = "apple"; 

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

     char str[] = "apple"; 
  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(); } 

如果您愿意,也可以迭代指向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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM