按值传递char*

Passing char* by value

本文关键字:char 按值传递      更新时间:2023-10-16

以下代码能工作吗?-

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

以下是函数的调用方式:

doSomething(testIn);
OtherFn(testIn);

char* in在代码的其他地方使用。。。并且我们将其按值传递给函数CCD_ 2。我知道当我们传递值时,存储在char*中的字符串的副本会复制到函数中。那么,当我们执行strcpy时,它会复制到本地副本还是作为参数传入的char* in

我的理解是我们需要做:doSomething(char* &in)。是这样吗?

当您只想修改指针指向的内容时,请使用:

doSomething(char* in)

所以,是的,

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

只要CCD_ 7指向足够的内存来保存CCD_。

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

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;