1

What data type would I use to store the address of other elements in an array.

As in, element 0 of an array has the address of element 5. And so on..

ksandarusi
  • 150
  • 4
  • 16

2 Answers2

1

A pointer can be converted into an int (or a long if you are doing 64-bit and your c compiler defines long as 64 bits). Then you need only get the address of the element you are trying to point to.

int test[10];
test[0] = (int)&test[5];
Tawnos
  • 1,877
  • 1
  • 17
  • 26
  • 1
    `intptr_t` might be a better type choice, as that type is guaranteed to be able to hold a pointer value. – M.M Apr 22 '14 at 02:21
  • Wouldn't that be `uintptr_t`? – Casper Beyer Apr 22 '14 at 03:12
  • I won't edit, I'd basically have to rewrite the entire post :) `intptr_t` is defined on the system if and only if there's an integral type that's big enough. AFAIK there is no difference between using this and `uintptr_t` – M.M Apr 22 '14 at 03:24
1

The address of an element has a different data type to the element. So your code is going to have to involve some type conversion.

To do it with minimal casting:

T some_object;

void *array[20];
array[0] = &some_object;
array[5] = &array[0];

// ....

T *some_ptr = *(void **)array[5];
M.M
  • 138,810
  • 21
  • 208
  • 365
  • @Peter, that would rely on `void *` and `T *` having identical representation and alignment requirements. – M.M Apr 22 '14 at 02:20
  • It also missed an indirection. Btw, all of this is only implementation defined, isn't it? – Peter - Reinstate Monica Apr 22 '14 at 02:21
  • I'm also not sure whether the OP wants to involve a separate T. My gut feeling is that the projection of recursive self referencing into the type system is the point here. Because in effect an element could hold a ******T, if the pointing is chained far enough. – Peter - Reinstate Monica Apr 22 '14 at 02:23
  • My version is well-defined, any pointer can be converted to `void *` and then have the original pointer retrieved. However my version is less useful if the OP intends to have longer chains of pointers , in that case he's probably better off using your idea and making that assumption. – M.M Apr 22 '14 at 02:23
  • Thanks for the bit about void *. – Peter - Reinstate Monica Apr 22 '14 at 02:35