双指针与单指针 [英] double pointer vs single pointer

查看:142
本文介绍了双指针与单指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释一下为什么下面代码片段中主函数中变量i的值不能通过函数test1进行更改而通过test2进行更改的原因吗?我认为单个指针应该足以更改i的值.我们为什么要使用双指针?

Can someone explain / give a reasoning to me on why the value of variable i in main function in below code snippet does not change via function test1 while it does change via test2? I think a single pointer should be sufficient to change the value of i. Why are we supposed to use double pointer?

#include <stdio.h>

void test1(int* pp)
{
   int myVar = 9999;
   pp = &myVar;
}

void test2(int** pp)
{
   int myVar = 9999;
   *pp = &myVar;
}

int main()
{
   printf("Hej\n");
   int i=1234;
   int* p1;

   p1 = &i;

   test1(p1);
   printf("does not change..., p1=%d\n",*p1);

   test2(&p1);
   printf("changes..., p1=%d\n",*p1);
   return 0;
}

推荐答案

在C中,参数按值传递.这意味着在test1中,当您传递pp时,将对指针进行复制,而在更改指针时,将对指针进行更改,而不是对指针本身进行更改.使用test2时,副本是双指针,但是当您取消引用并在此处分配

In C parameters are passed by value. This means that in test1 when you pass pp a copy is made of the pointer and when you change it the change is made to the copy not the pointer itself. With test2 the copy is of a double pointer but when you dereference and assign here

*pp = &myVar;

您正在更改所指向的内容,而不是更改pp本身.请注意,test2中的这种行为是未定义的,如此处其他一些答案中所述

you are changing what is being pointed to, not changing pp itself. Take note that this behaviour in test2 is undefined as is documented in some of the other answers here

这篇关于双指针与单指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆