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;
}
pmor
  • 5,392
  • 4
  • 17
  • 36
  • 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. – Oliver Charlesworth May 31 '14 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. – Cheers and hth. - Alf May 31 '14 at 10:48

1 Answers1

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.

Community
  • 1
  • 1
Columbo
  • 60,038
  • 8
  • 155
  • 203