简体   繁体   中英

Dereferencing pointer to void

I am working on an implementation of a hashmap in C, and the function for CMapPut is defined as follows:

void CMapPut(CMap *cm, const char *key, const void *elemAddr) 

My question is how do I retrieve the actual value of the element passed into the map? That is, when the client passes in the variables, he passes in the address of the value. In this case it appears to be a void * though, and of course you can't dereference a void * . Any tips?

You should be able to cast the pointer to the type you need:

typedef struct {
    ...
} CMyType;

...

CMyType myinstance;
CMapPut(cm, "key", &myinstance);

I guess you'll store the pointer as const void* . I guess you have a function like CMapGet , you use to retrieve your mapped objects like this:

void *CMapGet(CMap *cm, const char *key);

...

CMyType* myinstance_ptr = CMapGet(cm, key);

Cast your void * to your appropiate type, as mentioned by others. Second, you don't have to const your attribute elemAddr . It's no use, since you probably want to return a non-const pointer anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM