gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:42:02 25 4
gpt4 key购买 nike

我发现,使用一些预定义的函数,我应该将数据转换为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com