gpt4 book ai didi

C struct和malloc问题(C)

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

令人惊奇的是,即使是最小的程序也会在 C 语言中造成如此多的麻烦。

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

typedef struct node {
int value;
struct node *leftChild;
struct node *rightChild;
} node;

typedef struct tree {
int numNodes;
struct node** nodes;
} tree;

tree *initTree() {
tree* tree = (tree*) malloc(sizeof(tree));
node *node = (node*) malloc(sizeof(node));
tree->nodes[0] = node;
return tree;
}

int main() {
return 0;
}

编译器说:

main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token

你能帮忙吗?

最佳答案

您正在使用两个名为 treenode 的变量,但您也有结构 typedefed as treenode

更改您的变量名称:

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

typedef struct node {
int value;
struct node *leftChild;
struct node *rightChild;
} node;

typedef struct tree {
int numNodes;
struct node** nodes;
} tree;

tree *initTree() {
/* in C code (not C++), don't have to cast malloc's return pointer, it's implicitly converted from void* */
tree* atree = malloc(sizeof(tree)); /* different names for variables */
node* anode = malloc(sizeof(node));
atree->nodes[0] = anode;
return atree;
}

int main() {
return 0;
}

关于C struct和malloc问题(C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4768582/

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