Search code examples
cpointersmemorymallocrealloc

How to change saved address after reallocation


struct AD_SINT32Type* = NULL;
foo = (struct mystructArray*)malloc(sizeof(struct mystructArray));
foo[0].x = 45;
foo[0].y = 90;
coords[0] = &foo[0];


foo = (struct mystructArray*)realloc(foo, 2 * sizeof(struct mystructArray));
foo[1].x = 30;
foo[1].y = 15;
coords[1] = &foo[1];

After this code "coords[1]" points as intended, but "coords[0]" points to an the old address before the reallocation. Is there a way to automatic adapt the address "coords[0]" points to?


Solution

  • There is no fully "automatic" way to do this, but in cases like this where reallocation is needed, you often see the use of "offset pointers." So instead of this:

    coords[0] = &foo[0];
    

    You'd change the type of coords to something like ptrdiff_t[] and do this:

    coords[0] = &foo[0] - foo;
    

    This way, you save not the actual pointer, but the offset from the beginning of the allocation. And that value will never need to change.