1

let's assume I have a function that takes a pointer to pointer like this:

void foo (int** p){


// do stuff

}

my question is how can i pass a pointer to pointer to this function without making temporary pointer?

// sample code:
int a=10;
int* pa=&a;    // temporary pointer
foo (&pa);     //  passes a pointer to pointer , but requires a temporary pointer

foo (&&a);     // this does not compile

is there anyway to achieve this?

6
  • 1
    Not in standard C++. Commented Sep 14, 2017 at 13:28
  • 2
    So what should p point to if you don't have a temporary pointer? Commented Sep 14, 2017 at 13:29
  • 1
    What do you expect to achieve? The type of each arguments passed to a function must generally match the type expected by the function. Commented Sep 14, 2017 at 13:30
  • Why would you pass a pointer into a function that did not point to a real variable outside the function? What is it that you are trying to do? Commented Sep 14, 2017 at 13:37
  • I can't think of a context in which this would even make sense. Even if you had a temporary that lasted as long as the function call, you wouldn't be able to store it or anything because the temporary would die right after. And you're not using the first-level pointer, so writing to that isn't going to get anywhere. But writing to the int could be done with an int*. Commented Sep 14, 2017 at 13:48

2 Answers 2

2

In short, no. You can't have the address of the address of something that does not exist. That is why you need to declare a pointer to the address and then get the address of that pointer.

Address    Value  Symbol
0x20       0xFF   a
0x30       0x20   pa

You have to think about it like chaining them together. pa contains a value that points to the address of a. If you don't have pa you have no indirect reference to a and therefore cant get the pointer to the address as you just have the value and the address of a. Does that make sense?

Think of it like you can't point to yourself because you are, in fact, yourself but someone else can point to you.

Sign up to request clarification or add additional context in comments.

Comments

1

It is not possible. int** points to a memory cell holding int* value. This memory cell should be explicitly allocated.

You can however wrap foo calls into a inline function or macro which will do that:

inline void foo_(int* p) { int** p2 = &p; foo(p2); }

#define foo_(p) do { int* p1 = p; int** p2 = &p1; foo(p2); } while(0)

1 Comment

You shouldn't propose #define as inline function replacement, it a bad practive and more like C, not C++. Leave inlining to compiler

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.