簡體   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