2015-11-05 47 views
2

我想通過使用堆棧來反轉char *。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(); 
} 

在第二while循環,我不知道如何給每個字符從堆棧的頂部爲char *海峽分配。

+1

你不應該只是遍歷它向後並將其複製到一個新的緩衝區? – Cebtenzzre

回答

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

感謝您提醒我「apple」是一個const char []。 – Lynn

+0

@Lynn,不客氣。很高興能夠提供幫助。 –

1

您也可以迭代的指針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(); 
}