void指针作为参数 [英] void pointer as argument
问题描述
下面的C代码片段:
[...]
void f1(void* a){
printf("f(a) address = %p \n",a);
a = (void*)(int*)malloc(sizeof(int));
printf("a address = %p \n",a);
*(int*)a = 3;
printf("data = %d\n",*(int*)a);
}
void f(void){
void* a1=NULL;
printf("a1 address = %p \n",a1);
f1(a1);
printf("a1 address = %p \n",a1);
printf("Data.a1 = %d\n",*(int*)a1);
}
[...]
结果
a1 address = (nil)
f(a) address = (nil)
a address = 0xb3f010
data = 3
a1 address = (nil)
Segmentation fault (core dumped)
为什么不 A1
保持已分配给它的函数地址?
Why doesn't a1
keep the address that has been assigned to it in the function?
推荐答案
由于这是C,你不能通过引用传递指针而不指针传递到指针(如无效**
,而不是无效*
指向指针)。您需要返回新指针。发生了什么:
As this is C, you cannot pass the pointer by reference without passing in a pointer to the pointer (e.g., void **
rather than void *
to point to the pointer). You need to return the new pointer. What is happening:
f(a1);
推动指针( NULL
)的 A
值作为栈参数值。 A
拿起这个值,然后重新分配本身就是一个新的值(的malloc
ED地址)。因为它是按值传递,没有为改变A1
。
Pushes the value of the pointer (NULL
) as the stack parameter value for a
. a
picks up this value, and then reassigns itself a new value (the malloc
ed address). As it was passed by value, nothing changes for a1
.
如果这是C ++,你可以达到你做引用传递指针想要什么:
If this were C++, you could achieve what you wanted by doing passing the pointer by reference:
void f(void *&a);
这篇关于void指针作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!