我提出了一个问题,例如,当我做第一个节点后,我没有为节点提供足够的内存firstNode = (node)malloc(sizeof(node)).以下是*node的结构和使用malloc函数的insert函数.
typedef struct treeNode *node;
struct treeNode {
node left;
node right;
int data;
};
node firstN;
node secondN;
node insert(int a, node t){
if(t==NULL){
t = (node)malloc(sizeof(node));
t->data = a;
t->left = NULL;
t->right = NULL;
} else {
if(a < t->data){
t->left = insert(a, t->left);
}else if(a > t->data){
t->right = insert(a, t->right);
}
}
return t;
}
Run Code Online (Sandbox Code Playgroud)
这是main()我用malloc测试插入过程(我没有使用上面定义的插入函数,因为我仍在主要逐行测试).
firstN=(node)malloc(sizeof(node)*10);
firstN->data=1;
firstN->right=NULL;
firstN->left=NULL;
firstN->right=(node)malloc(sizeof(node)*10);
Run Code Online (Sandbox Code Playgroud)
对我来说有趣的是,虽然上面的工作,只是正常做(节点)malloc(sizeof(节点))(没有乘以10)不适用于第二个实例,firstN-> right.
我想知道为什么代码没有提供足够的内存,如果这是正确的情况.