2014-09-11 86 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; 
}