双指针用法

时间:2010-06-24 08:34:26

标签: c++ pointers

请查看以下代码:

#include <stdio.h>
#include <iostream>

using namespace std;
typedef struct MyType{
int num1;
};

void test(MyType **src)
{
 MyType *ret=new MyType;
 ret->num1=666;
 *src=ret;
}

int main(){
 MyType  *mSrc;
 test(&mSrc);
 printf("%d Address\n",mSrc);
 printf("%d Value \n",mSrc->num1);
}

我想知道test()方法是否已经实现如下,为什么调用者看不到test()方法中的指针赋值?

 void test(MyType *src)
    {
     MyType *ret=new MyType;
     ret->num1=666;
     src=ret;     //Why this assignment is only valid inside this method?
    }

如何在不使用签名中的双指针的情况下实现此功能?

3 个答案:

答案 0 :(得分:5)

  void test(MyType *src)

这里src只是test函数中的局部变量,它是传递给它的指针的副本。分配给局部变量对调用者没有任何影响。

如果您希望src引用您传入的相同变量,请使用reference

void test(MyType *&src)

答案 1 :(得分:4)

因为您传递了src指针的副本,而您只修改了函数内的副本。

答案 2 :(得分:1)

因为与src一起传递的是指针指向的地址。如果你改变它,它只会在函数内部改变。

就像你传递一个整数并改变它的值一样。该值仅在函数内部更改。

在C中,一切都是call by value,这就是为什么我们有“特殊”值(但它们仍然是值),可以指向某个位置。