开发者

Double Pointer Usage

开发者 https://www.devze.com 2023-01-05 01:37 出处:网络
Please take a look at following code: #include <stdio.h> #include <iostream> using namespace std;

Please take a look at following code:

#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);
}

I am wondering if the test() method had been开发者_如何学运维 implemented as follows,why the pointer assignment inside test() method is not visible to the caller?

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

How do I implement this function without using a double pointer in the signature?


  void test(MyType *src)

Here src is just a local variable within the test function, it's a copy of the pointer you passed to it. Assigning to a local variable doesn't have any effect on the caller.

If you wanted src to refer to the same variable you passed in, use a reference

void test(MyType *&src)


because you pass a copy of src pointer and you only modify the copy inside the function.


Because the value that is passed with src is the address where the pointer points to. If you change it, it is only changed inside the function.

It is the same thing as if you would pass an integer and change its value. The value is only changed inside the function.

In C, everything is call by value, that is why we have "special" values (but they are still values), that can point to some location.

0

精彩评论

暂无评论...
验证码 换一张
取 消