tags:

views:

94

answers:

3

Greetings all,

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?

+4  A: 

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

Daniel Băluţă
+5  A: 

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)
nos
when I use *
umanga
Perhaps you're compiling it as C, not C++,or you mistyped something
nos
+1  A: 

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.

Felix Kling