简体   繁体   English

c-将指针传递给具有void * variable参数的函数

[英]c - passing a pointer to a function with a parameter of void* variable

I want to pass a pointer to a variable. 我想传递一个指向变量的指针。 Sometimes it would be an integer and sometimes maybe a character. 有时是整数,有时是字符。 In the example below i pass the pointer p to CreateObject but when i try to retrieve the value of the variable the pointer points to i get an awkward result: 在下面的示例中,我将指针p传递给CreateObject但是当我尝试检索变量的值时,该指针指向我却得到了一个尴尬的结果:

int i =0;
int *p = malloc(sizeof(int));
*p = i;

ObjectP object = CreateObject(p);

Say i want to cast it back to an int and display it: 说我想将其投射回int并显示它:

void CreateObject(void *key)
{
   printf("%d\n", (int)key);
}

I get: 160637064 instead of 0. What am i getting instead of the integer i assigned previously and how do i retrieve it instead of the current value? 我得到:160637064,而不是0。我得到的是什么而不是我先前分配的整数,我如何检索它而不是当前值?

This: 这个:

(int) key

is not dereferencing the pointer to access the data it points at, it's re-interpreting the pointer value (the address) itself as the integer. 不会取消引用指针以访问其指向的数据,而是将指针值(地址)本身重新解释为整数。

You need: 你需要:

printf("%d\n", *(int *) key);

You're typecasting a pointer to an integer. 您正在强制转换一个指向整数的指针。 This means that you simply get the address. 这意味着您只需获取地址。 After all, a pointer is just an address. 毕竟,指针只是一个地址。

You probably want to dereference the pointer instead of casting it. 您可能想取消引用指针而不是强制转换指针。 *(int*)key would do that. *(int*)key可以做到这一点。

You're printing the pointer, ie. 您正在打印指针,即。 the address, not the value that it's pointing to. 地址,而不是它指向的值。

Use this to print the value: 使用它来打印值:

void CreateObject(void *key)
{
   printf("%d\n", *(int*)key);
}

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

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