I am fiddling around with and learning about void pointers and linked lists and I think I may have to concept and application a little wrong.
Currently, I have a void pointer which points to the address of a struct in memory. I am then trying to access this struct via casting the void pointer to that struct. However, I am not getting the expected value only 0.
Code is as follows.
void *data = ListGetItemAtIndex(freeList, i); // returns void *
memoryBlock *block = (memoryBlock *) data;
printf("%ld\n\n", block->startAddress);
The struct:
typedef struct
{
size_t startAddress;
size_t memory;
} memoryBlock;
Address when struct was added:
0x5593c4812720
Address of void *:
0x5593c4812720
The question at heart is, how do I use this void pointer to access the data in the struct.
Requested example :
Block creation
static memoryBlock* CreateMemoryBlockPointer(size_t startAdress, size_t size)
{
memoryBlock block;
block.startAddress = startAdress;
block.memory = size;
return malloc(sizeof(block));
}
Assignment:
memoryBlock *ptr = CreateMemoryBlockPointer(StartAddress, size);
// Add initial 1st element
ListAddTail(freeList, ptr);
Prototype:
int ListAddTail(linkedList *list, void* data)
Add to list
el->data = data;
el->next = NULL;
Solved, see :
Allocate the memory first, then write into the memory, e.g.:
memoryBlock *block = malloc(sizeof(*block)); block->startAddress = startAddress;
etc. then return block; at the end of the function –