2015-11-05 49 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(); 
}