空指针作为参数 [英] void pointer as argument

查看:25
本文介绍了空指针作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 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,所以你不能通过引用传递指针而不传递指向指针的指针(例如,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 malloced 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);

这篇关于空指针作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆