gpt4 book ai didi

c - Null/void 指针不正确的值

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:41 24 4
gpt4 key购买 nike

我们在我们的一个函数中返回一个指向结构的指针。当我们在 main 中打印出结构的值之一时,它是正确的。但是,当我们将该指针传递给另一个函数并尝试访问一个值时,它会打印出一个不正确的值。看起来那个值是一个地址。

这些调用主要是:

struct temp * x = doThis();
printf("x->var1 = %d\n", x->var1);
doThat(&x);

在 doThat 中,我们打印出:

void doThat(void * x)
{
struct temp * x2 = (struct temp *) x;
printf("x2->var1 %d", x2->var1);
}

doThis 函数返回一个空指针,doThat 函数接受一个空指针作为参数。

最佳答案

doThat 中,您将 x 转换为 struct temp*,但您传入的是 struct temp**

您可以在此处看到类似的结果:running code .

改变自:

struct temp * x2 = (struct temp *) x;
printf("x2->var1 %d", x2->var1);

收件人:

struct temp ** x2 = (struct temp **) x;
printf("(*x2)->var1 %d", (*x2)->var1);

会解决这个问题。或者,不要通过更改以下内容将指针传递给指针:

doThat(&x);

收件人:

doThat(x); /* <= Note: Don't take the address of x here! */

关于c - Null/void 指针不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16659317/

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