This feels like a silly question, but I just can't work out a clean solution and can't find a similar question in the mass of other pointer related questions.
I have some dynamically allocated memory of unknown type and want to store a pointer inside it at the start. Dynamic memory returned by malloc should be suitably aligned so I don't think I have to worry about alignment when writing to the start of the allocated block.
This is my code, which works, but I'm representing a pointer as a 64-bit integer and want to do it in a more clean/portable way:
void *my_area = malloc(512);
void *my_pointer = get_my_pointer();
((long long *) my_area)[0] = (long long) my_pointer;
The cast to long long is just extra baggage. Cast to void * instead.
void *my_area = malloc(512);
void *my_pointer = get_my_pointer();
((void **) my_area)[0] = my_pointer;
(I assume that this is for some kind of freelist or the like, i.e., you don't need to use the structure at the same time.)
What will be found in my_area[0] is pointer to something, right ?
Then you can allocate my_area to be of type void **, which represent a pointer to a pointer containing memory area.
void **my_area = malloc(512 * sizeof(*my_area)); // alloc 512 pointer sized memory blocks
void *my_pointer = get_my_pointer();
my_area[0] = my_pointer;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With