[英]Creating a pointer, pass a pointer, pass an address of a pointer
这两个代码有什么区别?
任何人都可以像这样向我解释: #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
非常感谢!
我想你被太多的指针弄糊涂了。 指针令人恐惧是有原因的,但在许多方面它们就像任何其他变量一样。
修改按值传递给 function 的指针对传递给 function 的指针没有影响。
稍微减少你的例子的可怕性,我们得到:
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
}
这两个示例(我的和你的)之间的区别在于一个是按值传递,另一个是按引用传递(通过指针)。
此外,在您的代码(两个版本)中存在 memory 泄漏,因为您没有删除通过new
分配的 char 数组。
首先:
我有一张纸,上面有一些毫无意义的涂鸦。
我把那些涂鸦抄在另一张纸上,作为礼物送给你。
你擦掉自己纸上的涂鸦,然后在上面写下你的地址。
正如你所看到的,我的那张纸上仍然只是涂鸦,我不知道你住在哪里。
第二:
我有一张纸,上面有一些毫无意义的涂鸦。
我告诉你那张纸是。
你go到那个地方,擦掉涂鸦,写下你的地址。
如您所见,我的纸上现在有您的地址。
(简短版本:分配给函数的非引用参数在 function 之外没有任何影响。指针没有什么特别之处。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.