问题描述
这两个代码有什么区别?
有人可以像#1 do,#2 do,#3 do
这样向我解释吗?
我对这些代码的用途有所了解,但我不确定。
void test(char *msg) {
/*3*/ msg = new char[5];
}
int main() {
/*1*/ char *msg;
/*2*/ test(msg);
}
// I think
// #2 Pass the pointer
// #3 Allocates 5 bytes char in address where the pointer points
void test(char **msg) {
/*3*/ *msg = new char[5];
}
int main() {
/*1*/ char *msg;
/*2*/ test(&msg);
}
// I think
// #2 Pass the address to the 4 bytes memory block where the pointer is stored
// #3 Allocates 5 bytes char to the prevIoUs 4 bytes + allocates new 1 byte
非常感谢!
解决方法
我想您对太多的指针感到困惑。指针之所以令人恐惧是有原因的,但是在许多方面,它们就像其他任何变量一样。
修改按值传递给函数的指针对传递给该函数的指针没有影响。
减轻您的示例的恐惧感,我们得到:
void test(std::string msg) {
msg = std::string("Hello World");
}
int main() {
std::string msg;
test(msg);
std::cout << msg; // is still an empty string !
}
void test(std::string* msg) {
*msg = std::string("Hello World");
}
int main() {
std::string msg;
test(&msg);
std::cout << msg; // prints hello world
}
两个示例(分别是您的和)之间的区别在于,一个示例是通过值传递的,另一个示例是通过引用传递的(通过指针)。
此外,在您的代码(两个版本)中,都有内存泄漏,因为您没有删除通过new
分配的char数组。
第一个:
我有一张纸,上面写着一些毫无意义的涂鸦。
我将这些涂鸦复制到另一张纸上,然后作为礼物送给您。
您可以擦除自己纸上的涂鸦,并在上面写下您的地址。
如您所见,我的纸上仍然只写满了涂鸦,我不知道您住在哪里。
第二个:
我有一张纸,上面写着一些毫无意义的涂鸦。
我告诉你那张纸是。
您去那个地方,清除涂鸦,然后写下您的地址。
如您所见,我的纸上现在有您的地址。
(简短版本:分配给函数的非引用参数在该函数之外无效。指针没有什么特别的。)