我想传递一个指向变量的指针.有时它会是一个整数,有时可能是一个字符.在下面的例子中我传递指针p,CreateObject但当我尝试检索指针指向的变量的值时,我得到一个尴尬的结果:
int i =0;
int *p = malloc(sizeof(int));
*p = i;
ObjectP object = CreateObject(p);
Run Code Online (Sandbox Code Playgroud)
假设我想将它强制转换为int并显示它:
void CreateObject(void *key)
{
printf("%d\n", (int)key);
}
Run Code Online (Sandbox Code Playgroud)
我得到:160637064而不是0.我得到的是什么,而不是我之前分配的整数,我如何检索它而不是当前值?
这个:
(int) key
Run Code Online (Sandbox Code Playgroud)
它没有取消引用访问它指向的数据的指针,它将指针值(地址)本身重新解释为整数.
你需要:
printf("%d\n", *(int *) key);
Run Code Online (Sandbox Code Playgroud)