gpt4 book ai didi

c - typedef 有什么用,它的正确用途是什么?

转载 作者:行者123 更新时间:2023-11-30 16:10:30 24 4
gpt4 key购买 nike

    #include <stdio.h>
#include <stdlib.h>

typedef struct
{
int val;
struct tree *left, *right;
}tree;

struct tree *root;

struct tree *add_vertex(int val)
{
struct tree *root = malloc(sizeof(struct tree*));
root->val = val;
root->left = NULL;
root->right = NULL;
return root;
}

void print_tree(struct tree *root)
{
printf("%d\n", root->val);
if(root->left == NULL)
return;
else
print_tree(root->left);
if(root->right == NULL)
return;
else
print_tree(root->right);
}

int main() {
struct tree *root = NULL;

root = add_vertex(1);
root->left = add_vertex(2);
root->right = add_vertex(3);
root->left->left = add_vertex(4);
root->left->right = add_vertex(5);
root->right->left = add_vertex(6);
root->right->right = add_vertex(7);

print_tree(root);

return 0;
}

这段代码正在生成

prog.c: In function 'add_vertex':
prog.c:15:9: error: dereferencing pointer to incomplete type 'struct tree'
root->val = val;
^'

删除typedef并进行特定的更改,效果很好。

最佳答案

问题是

typedef struct
{
int val;
struct tree *left, *right;
}tree;

定义了一个名为tree类型,它是一个未命名结构的类型。

您的代码中没有定义结构树

如果删除 typedef,您将定义一个名为 tree 的结构,并且您的代码将正常工作。

<小时/>

也就是说,如果你想使用typedef,你可以这样做

struct tree
{
int val;
struct tree *left, *right;
};

typedef struct tree tree;

//......

tree *add_vertex(int val) //no need to use struct keyword anymore
{
tree *root = malloc(sizeof(*root));
root->val = val;
root->left = NULL;
root->right = NULL;
return root;
}

关于c - typedef 有什么用,它的正确用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58874083/

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