Null/void指针值不正确

use*_*248 0 c struct pointers

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

这些电话是我们的主要:

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

在doThat中,我们打印出来:

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

doThis函数返回一个void指针,doThat函数将void指针作为参数.

Bil*_*ill 8

在doThat你铸造x是一个struct temp*,但你传入一个struct temp**.

您可以在此处看到类似的结果:运行代码.

改变自:

struct temp * x2 = (struct temp *) x;
printf("x2->var1 %d", x2->var1);
Run Code Online (Sandbox Code Playgroud)

至:

struct temp ** x2 = (struct temp **) x;
printf("(*x2)->var1 %d", (*x2)->var1);
Run Code Online (Sandbox Code Playgroud)

会解决这个问题.或者,不要通过更改来传递指针指针:

doThat(&x);
Run Code Online (Sandbox Code Playgroud)

至:

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