0
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?

Pawan
  • 1,537
  • 1
  • 15
  • 19
Jiggy
  • 33
  • 3

4 Answers4

3

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 2
    The difference of two pointers yields a `ptrdiff_t`. Any other type might loose information. On 64 bit architectures (P64), an `uint32_t` **will** loose information. – too honest for this site Dec 14 '15 at 14:48
  • @Olaf: I have updated my answer to use `ptrdiff_t`. At least now nobody can complain that I've done something dirty. On 64-bit you will only lose information storing into a 32-bit int if you have a huge array. Just so we're clear. – John Zwinck Dec 14 '15 at 16:10
  • "something like" still is suspectible imo. `ptrdiff_t` is exactly designed for such. However, as the difference will always be `>= 0` and you actually calculate an index, `size_t` would also be acceptable. – too honest for this site Dec 14 '15 at 16:23
1

Is there a way to automatic adapt the address "coords[0]" points to?

No.

See How to update other pointers when realloc moves the memory block?

Community
  • 1
  • 1
Andrew Henle
  • 32,625
  • 3
  • 24
  • 56
0

Is there a way to automatic adapt the address "coords[0]" points to?

No. C does not keep track where you store addresses. If you need this, it's your job to keep track.

Another idea is to think outside the box:

  • can you restructure your data in a way you don't need to store more than one pointer to the start of the dynamic array?
  • can you work with offsets instead?
Jens
  • 69,818
  • 15
  • 125
  • 179
0

Just make coords a size_t [] (this is the correct type) and store indexes into foo instead of absolute addresses.

Alternatively, after a realloc of foo, you can update all coords entries in a loop.

But the first version migh not be much slower than using addresses, you benchmark before going complicated.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52