0

I have a problem with pointer type when writing my program. The code looks like follows:

datatype B;
int func(datatype* A){
 A=&B;
};
int main(int argc,char** argv){
 dataType* mainA=new dataType;
 func(mainA);
}

What I want is after excuting func(mainA). mainA is point to B. I know my code is wrong, after that, mainA did not change. I thought this should like something called call by reference. Can anyone help me solve this problem?

Many thanks.

2 Answers 2

3

You can make the parameter a reference to pointer. Lastly, a pointer is also an object and can be modified through references.

int func(datatype*& A)
{
    A = &B;
}

However, I would prefer to return the result and assign it:

datatype* func()
{
    return &B;
}

// […]

dataType* mainA = func();
0
1

You would have to declare the A parameter as a reference to a pointer:

int func(datatype *&A){

Now the pointer itself will be passed by reference so func() will be allowed to change mainA if you pass it in.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.