2014-09-11 85 views
-3

我有一個名爲thingy的對象,其中有一個方法playWithString(char * text)。 我有一個字符數組,如 char testString = nullptr; 我想的TestString進入thingy.playWithString(炭文本)C++數組傳遞到函數

我最初通過將這個在playWithString方法開始嘗試這個 文本=新的char [128] 能正常工作在函數,但一旦函數結束,testString再次爲空。我如何讓它保留函數結果的價值?

+0

您能否提供您的實際代碼? ......但是如果你想在'playWithString'方法內改變你的char-pointer,你必須將它的參數改爲引用指針或指針指針。 – Sambuca 2014-09-11 06:06:58

+0

'char testString = nullptr;'不是一個數組。請澄清你的問題,添加一些現實的代碼。 – juanchopanza 2014-09-11 06:20:01

回答

0

您需要通過引用傳遞。這是發生了什麼事情:

void playWithString (char* myptr) { 
    myPtr = new char [128]; 
    //myPtr is a local variable and will not change the fact that testString still points to NULL 
    *myPtr = 'a'; 
    *myPtr = 'b'; 
} 

main() { 
    char *testString = NULL; //testString is not pointing to anything 
    playWithString(testString); 
    //tesString is still null here 

} 

解決方法:通過引用。注意playWithString的簽名中的&。

void playWithString (char* &myptr) { 
    myPtr = new char [128]; 
    //myPtr is a local variable and will not change the fact that testString still points to NULL 
    *myPtr = 'a'; 
    *myPtr = 'b'; 
} 

main() { 
    char *testString = NULL; //testString is not pointing to anything 
    playWithString(testString); 
    //tesString is still null here 

} 
0

這聽起來像你試圖修改指針,而不是指針指向的數據。創建函數時,除非將參數設置爲指針或引用,否則參數通常按值傳遞。這意味着參數被複制,因此賦值給參數只會修改副本,而不是原始對象。在參數是一個指針(數組參數表示爲指向數組中第一個元素的指針)的情況下,指針正在被複制(儘管它指向的內容在函數的外部和內部都是相同的)。使用這個指針,你可以修改它所指向的內容,並使該效果在函數之外保持;然而,修改指針本身(例如,使其指向不同的數組)只是修改副本;如果你想要這樣的突變持續到函數之外,你需要一個額外的間接層。換句話說,您需要將指針或引用傳遞給指針,以便能夠更改其目標。

P.S.正如其他人所指出的,對於使用字符串,您應該使用std::string。這就是說,理解底層機制以及如何在學習時使用char*是很好的。

0

也許你應該使用C++字符串(std :: string)?

#include <string> 
#include <iostream> 

class A { 
public: 
    void foo(const std::string& s) { 
     std::cout << s << std::endl; 
    } 

}; 

int main(int argc, char* argv[]) { 

    A a; 

    std::string str = "Hello!"; 
    a.foo(str); 

    return 0; 
}