2

Is it possible to automatically update pointer value inside a structure when memory allocation goes later? Please, look at the code.

struct S {void *ptr;};

void *p;
struct S ST= {p};

int main() {
    p = new int;
    void* b = ST.ptr; // b should be the same as p
    return 0;
}
2
  • 3
    If you're in C++, you could use a reference to the pointer. If you're in C, you could use a pointer-to-pointer. Commented May 31, 2014 at 10:18
  • You can change the order of actions, or which part of the code is responsible for allocating. Or, you can add another layer of indirection. But as always it's a good idea to look at the real problem, not the imagined technical solution to that problem. Which means, adding another layer of indirection, which comes at a cost, is probably not a good idea. It's a technical solution though. Commented May 31, 2014 at 10:48

1 Answer 1

2

You can simply hold an indirection:

C++:

struct S
{
    void*&  ptr; // ptr is now a reference to a pointer. Drawback: Has to be initialized.
};

This can be used as follows:

S s = {p};

But references as members are a controversial subject. In this case, the other way of indirection may be better:

C:

Maybe the new in your snippet was just for explanatory purposes, and you work with C (the elaborate type specifier in your code supports that argument).

struct S
{
    void**  ptr; // ptr is now a pointer to a pointer. Drawback: Can be zero.
};

In this case, you initialize ptr with the address of the pointer it should refer to:

struct S s = {&p}; // I don't know about list-initialization in C, so i'll stick to this

Subsequently, when dereferencing it you'll get an lvalue to p.

For differences between references and pointers, read this post.

And also don't forget about smart pointers. Maybe shared ownership is what you're looking for.

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

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.