下面的代码可以工作吗?
void doSomething(char* in)
{
strcpy(in,"mytext");
}下面是该函数的调用方式:
doSomething(testIn);
OtherFn(testIn);在代码中的其他地方使用了char* in ...我们通过值将其传递给函数doSomething。我知道当我们通过值传递时,存储在char*中的字符串的副本会被复制到函数中。那么,当我们执行strcpy时,它是复制到本地副本,还是复制到作为参数传入的char* in?
我的理解是我们需要做的是:doSomething(char* &in)。是那么回事吗?
发布于 2015-03-31 12:41:41
如果只想修改指针所指向的内容,请使用:
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;https://stackoverflow.com/questions/29360695
复制相似问题