0

I have a function whose parameter is a reference. I need to pass a pointer argument to this function. Is the below declaration valid for this situation? If not, what do I need to do?

function foo(int& myParam) {
    //some code here
}

//function call
int *myArg;
foo(myArg);
2
  • Did you try it? What did your compiler say? Commented Nov 11, 2016 at 17:01
  • See the answers posted they will do what you want. But the code you have should work, just not the way you expect. Know that a pointer is a memory address value which also happens to be an integer. So in your case you would be passing the reference to the pointer not the value it points to as argument to the function. So it will not have the value you expect and if you mess with it, it could cause some very unpredictable results. Commented Nov 11, 2016 at 17:09

2 Answers 2

4

To pass the pointer's value by reference, you must dereference the pointer. But in your situation, you never initialize the pointer, so dereferencing it will cause undefined behavior.

int* ptr;
int& ref = *ptr; // dereferencing garbage pointer

You can dereference the pointer and let the compiler turn the value into a reference, but you must have a valid pointer first, eg:

int *ptr = new int();
foo(*ptr)
delete ptr;

Or:

int i;
int *ptr = &i;
foo(*ptr)
Sign up to request clarification or add additional context in comments.

Comments

0

if you want to use the value pointed by myArg, you can simply code:

foo(*myArg);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.