我必须在 Flex/Yacc 上完成这个项目,其中我必须计算 Insiemistic 表达式的抽象语法树。但真正的问题出在 C 代码中。
我已经创建了这个函数,它创建了一个节点:
node_t * createNode(node_content_t nodecontent, int nodetype){
node_t *newNode = (node_t *) malloc(sizeof(node_t * ));
if(nodetype == 0){
newNode->content = (node_content_t)strdup(nodecontent.string);
}
else
newNode->content = nodecontent;
newNode->type = nodetype;
newNode->leftChild = NULL;
newNode->rightChild = NULL;
printf("Right Child in createNode: %p\n", newNode->rightChild);
return newNode;
}
如您所见,左子节点和右子节点都初始化为 null。但是当我尝试从函数中打印右子级的指针值时,它会更改值(通常为 0x23 或 0x53),从而导致分段错误。
node_t和node_content_t定义如下
typedef union{
char* string;
char singleletter;
}node_content_t;
typedef struct node node_t;
struct node{
node_content_t content;
int type; //0 for string, 1 for char
node_t *leftChild;
node_t *rightChild;
};
当我尝试在
createNode
中打印指针时,结果是0x0,我在这个函数printNode中打印了它,这应该打印整个树:
void printNode(node_t *n, size_t indent) {
char *indentation = malloc(sizeof(char) * indent);
for (size_t i = 0; i < indent; ++i) {
indentation[i] = ' ';
}
printf("LeftChild: %p\n", n->leftChild);
printf("RightChild: %p\n", n->rightChild);
switch (n->type) {
case 0: printf("%s%s\n", indentation, n->content); break;
case 1: printf("%s%c\n", indentation, n->content); break;
}
if (n->leftChild != NULL){
printNode(n->leftChild, indent+2);
}
if (n->rightChild != NULL){
printf("RightChild: %p\n", n->rightChild); //there
printNode(n->rightChild, indent+2);
}
printf("Non ci sono figli\n");
}
正如我所说,值发生变化,因此该功能不起作用,有什么想法吗?如果不在函数 addChild 中,我不会修改 rightChild 的值:
void addChild(node_t *parent, node_t *child) {
printf("Addchild\n");
printf("Right Child in createNode: %p\n", parent->rightChild);
if(parent->leftChild == NULL)
parent->leftChild = child;
else if(parent->rightChild == NULL && strcmp(parent->content.string, "co") != 0 ){
parent-> rightChild = child;
printf("Aggiunto figlio destro\nContent: %c\nType: %d\n", child->content, child->type);
}
else
printf("Error during child adding\n");
}
问题在于
malloc().node_t *newNode = (node_t *) malloc(sizeof(node_t * ));
只分配了指针的大小。
解决方法,改为node_t *newNode = malloc(sizeof *newNode );