gpt4 book ai didi

c - 为什么这三种方式在C代码中是不同的?

转载 作者:太空狗 更新时间:2023-10-29 15:14:26 25 4
gpt4 key购买 nike

这段代码有些问题。注意评论。为什么?

struct node
{
struct node *left;
struct node *right;
int value;
};

static struct node root2;

int main()
{
struct node *root = (struct node *) malloc(sizeof(struct node));

assert(root->left == NULL); /* not failed. Why? */
assert(root->right == NULL); /* not failed. Why? */

assert(root2.left == NULL); /* not failed. Why? */
assert(root2.right == NULL); /* not failed. Why? */

struct node root1;
assert(root1.left == NULL); /* this failed. Why? */
assert(root1.right == NULL); /* this failed. Why? */

free(root);

return 0;
}

最佳答案

对于 root1,您已经声明了一个节点的本地实例,它将位于堆栈中。你没有初始化它,所以它会包含垃圾。

对于 root2,您已经声明了一个全局实例。默认的启动代码会清除全局占用的内存。

对于 root,它将存在于堆中,并且包含垃圾。占用的内存是否包含0纯属运气。如果您使用 calloc 而不是 malloc,它会为您清除内存。

关于c - 为什么这三种方式在C代码中是不同的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5140862/

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