按值传递char *

时间:2015-03-31 04:36:36

标签: c++ parameter-passing

以下代码是否有效? -

void doSomething(char* in)
{
    strcpy(in,"mytext");
}

这里是如何调用函数的:

doSomething(testIn);
OtherFn(testIn);

char* in用于代码中的其他位置......我们将它按值传递给函数doSomething。我理解当我们通过值传递时,char*中存储的字符串的副本将复制到函数中。那么,当我们执行strcpy时,它会复制到本地副本还是作为参数传递的char* in

我的理解是:doSomething(char* &in)。是吗?

1 个答案:

答案 0 :(得分:3)

如果只想修改指针指向的内容,请使用:

doSomething(char* in)

所以,是的,

void doSomething(char* in)
{
   strcpy(in,"mytext");
}
只要in指向足够的内存来保存"mytest"和终止空字符,

就可以正常工作。

有时您想要修改指针指向的位置,例如,通过分配新内存。然后,您需要传递对指针的引用。

void doSomething(char*& in)
{
   in = new char[200];
   strcpy(in,"mytext");
}

并将其用作:

char* s = NULL;
doSomething(s);
// Now s points to memory that was allocated in doSomething.

// Use s


// make sure to deallocate the memory.
delete [] s;