gpt4 book ai didi

c - 指向结构体的指针

转载 作者:行者123 更新时间:2023-12-02 08:55:59 24 4
gpt4 key购买 nike

即使我没有分配内存并且已经在 main 中声明了指向结构二的指针,这也会给出正确的输出

    struct one
{
char x;
int y;
};

struct two
{
char a;
struct one * ONE;
};

main()
{
struct two *TWO;
scanf("%d",&TWO->ONE->y);
printf("%d\n",TWO->ONE->y);
}

但是当我在 main 之外的结构之后声明指向 2 的指针时,我会遇到段错误,但为什么在之前的情况下我没有遇到段错误

    struct one
{
char x;
int y;
};

struct two
{
char a;
struct one * ONE;
}*TWO;


main()
{
scanf("%d",&TWO->ONE->y);
printf("%d\n",TWO->ONE->y);
}

最佳答案

在这两种情况下,TWO 都是指向 struct Two 类型对象的指针

在情况 1 中,指针是狂野的,可以指向任何地方。

在情况 2 中,指针为 NULL,因为它是全局的。

但在这两种情况下,它都是一个不指向有效 struct Two 对象的指针。 scanf 中的代码将此指针视为引用有效对象。这会导致未定义的行为。

关于c - 指向结构体的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4825731/

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