c - c 中这两种转换格式 (void **) &a 和 (void *)a 的区别

标签 c casting

我发现,使用一些预定义的函数,我应该将数据转换为 void*,然后将其传递给函数。这很容易理解。

我的问题是这两个 Actor 之间有什么区别:

  1. (void **)&a
  2. (void*)a

我应该使用其中哪一个,有什么区别?

最佳答案

您写道,“这很容易理解”。显然不是。首先,您没有转换数据,数据没有发生任何变化。其次,使用 a&a 传递给函数的内容完全不同。 void 指针只是对某些数据的引用。底层数据类型(对于编译器来说)是未知的。因此,您无法执行指针算术等操作。

假设您 malloc() 一 block 内存来存储一些数据,返回的指针是值 0x2020 并分配给 x。现在假设 x 位于内存位置 0x1000 处的堆栈区域中。这意味着 x 是 0x2020。 *x 是您放入该 malloc 区域内的数据。现在重要的部分是.. &x 是 0x1000,它是 x 的内存地址,在我们假设的情况下,它位于堆栈上。以下示例演示了一些 void *void **。这只是一个快速示例,除了演示概念之外,不是做任何事情的正确方法。

#include <stdio.h>

struct t1 { int a; };
struct t2 { int b; };

int testvppa(void **pp){
    void *p = *pp;
    struct t1 * pt = (struct t1 *)p; // need to cast in order to de-reference
    return pt->a;
}
int testvppb(void **pp){
    void *p = *pp;
    struct t2 * pt = (struct t2 *)p; // need to cast in order to de-reference
    return pt->b;
}
int testvp(void *p, int which){
    if (which == 1)
    {
        return testvppa(&p);
    }
    else{
        return testvppb(&p);
    }
}

int main(){
    struct t1 stuffa = { 123 };
    struct t2 stuffb = { 456 };
    void * vp;

   printf("stuffa: {%d} @ %p\n", stuffa.a, &stuffa);
   printf("stuffb: {%d} @ %p\n", stuffb.b, &stuffb);

   vp = &stuffa;
   printf("vp: %p test: %d\n", vp, testvp(vp,1));

   vp = &stuffb;
   printf("vp: %p test: %d\n", vp, testvp(vp,2));
   return 0;
}

在我的机器上运行有以下结果:(请注意,指针的地址将会改变,但值 123 和 456 将相同。)

stuffa: {123} @ 0x7fff28116db0
stuffb: {456} @ 0x7fff28116dc0
vp: 0x7fff28116db0 test: 123
vp: 0x7fff28116dc0 test: 456

我的回答很可能会令人困惑而不是启发。这就是为什么你的问题的实际正确答案正是 Oli Charlesworth 在他的评论中所说的:“我建议先学习 C,然后发布问题”

关于c - c 中这两种转换格式 (void **) &a 和 (void *)a 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20357256/

相关文章:

C:非 ASCII 文本数据的 char 与 unsigned char

c - 汉明重量只写在二元运算中?

ios - 将 NSDictionary 转换为字典 Swift

java - 如何比较字符串的百分比?

c# - 获取 System.Type 并返回该类型的 IEnumerable

c - 使用 win32 和 C 从 WDK 驱动程序中的 UNICODE_STRING 中提取路径名组件

在 Linux 内核中创建您自己的自定义信号

c# - 如何将 DataSource 转换为 List<T>?

c++ - 为什么虚拟继承会导致指针偏移?

c++ - 在 C 中管理枚举变量(从 C++ 移植代码)