C struct和malloc问题(C)

Gal*_*Gal 4 c malloc struct

令人惊讶的是,即使是最小的程序也会在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;
}
Run Code Online (Sandbox Code Playgroud)

编译器说:

main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token 
main.c:18: error: expected expression before ')' token
Run Code Online (Sandbox Code Playgroud)

你能帮忙吗?

wkl*_*wkl 13

您正在使用命名的两个变量treenode,但你也有结构typedef编为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;
}
Run Code Online (Sandbox Code Playgroud)

  • @sombe - 你不必(在C中),从`void*`到你的指针类型的转换是隐式的. (2认同)

det*_*zed 5

treenode为你的情况是类型名称,不应在以后作为变量名.

tree *initTree() {
    tree *myTree = (tree*) malloc(sizeof(tree));
    node *myNode = (node*) malloc(sizeof(node));
    myTree->nodes[0] = myNode;
    return myTree;
}
Run Code Online (Sandbox Code Playgroud)