按值传递char*
Passing char* by value
以下代码能工作吗?-
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;
相关文章:
- 何时应通过引用传递矢量参数而不是按值传递矢量参数?
- C++类 - 初始化列表 - 递归 - 按值传递
- 将函数参数完美转发到函数指针:按值传递呢?
- 棘手的按值传递和按引用递归问题传递
- 不同于按值传递和常量引用传递的程序集
- 按值传递变量与按引用传递变量具有相同的结果
- 为什么按值传递QStringView比引用常量更快?
- 获取 std::函数以推断按引用传递/按值传递
- 在函数中按值传递 unordered_map/unordered_set 是否有效? C++
- C++/11 auto 关键字是在更有效时推导参数进行按引用传递,还是始终按值传递?
- 使用 enable_if 在按值传递与按引用传递之间更改函数声明
- 防止在按值传递对象(继承)时进行切片
- 按值传递类和结构
- C++按引用传递还是按值传递?
- 为什么在按值返回时创建临时对象,而不是在按值传递给函数参数时创建临时对象
- 可移动但不可复制的对象:按值传递还是按引用传递?
- const-ref传递的模板化参数是否经过优化,以便在足够小时按值传递
- 在C++中指针是按值传递的吗
- shared_ptr构造函数参数是否应按值传递
- 按值传递char*