首页 文章

空/无效指针值不正确

提问于
浏览
-1

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

这些电话是我们的主要:

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函数返回一个void指针,doThat函数将void指针作为参数 .

1 回答

  • 8

    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! */
    

相关问题