简体   繁体   English

解引用指向void的指针

[英]Dereferencing pointer to void

I am working on an implementation of a hashmap in C, and the function for CMapPut is defined as follows: 我正在用C实现哈希图的实现,并且CMapPut的函数定义如下:

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 * . 在这种情况下,它似乎是一个void * ,当然您不能取消引用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* . 我想您会将指针存储为const void* I guess you have a function like CMapGet , you use to retrieve your mapped objects like this: 我猜您有一个类似CMapGet的函数,您可以像这样检索映射的对象:

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

...

CMyType* myinstance_ptr = CMapGet(cm, key);

Cast your void * to your appropiate type, as mentioned by others. 正如其他人所提到的,将您的void *为您的适当类型。 Second, you don't have to const your attribute elemAddr . 其次,您不必const属性elemAddr It's no use, since you probably want to return a non-const pointer anyway. 这没有用,因为您可能仍然想返回一个非常量指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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