void 指针作为参数 [英] void pointer as argument
问题描述
以下 C 代码段:
[...]
void f1(void* a){
printf("f(a) address = %p
",a);
a = (void*)(int*)malloc(sizeof(int));
printf("a address = %p
",a);
*(int*)a = 3;
printf("data = %d
",*(int*)a);
}
void f(void){
void* a1=NULL;
printf("a1 address = %p
",a1);
f1(a1);
printf("a1 address = %p
",a1);
printf("Data.a1 = %d
",*(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 语言,如果不传入指向指针的指针,就不能通过引用传递指针(例如,void **
而不是 void *
指向指针).您需要返回新指针.发生了什么:
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 want by passing the pointer by reference:
void f(void *&a);
这篇关于void 指针作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!