C 分段故障自适应哈夫曼树
我试图实现自适应哈夫曼代码,但在尝试构建树时,在addnode()函数的“currentNYT->lchild=newNYT;”行执行代码时出现了分段错误 谁能帮我一下吗?这可能是我不知道的一些简单的事情。有一段时间没用C了C 分段故障自适应哈夫曼树,c,segmentation-fault,huffman-code,adaptive-compression,C,Segmentation Fault,Huffman Code,Adaptive Compression,我试图实现自适应哈夫曼代码,但在尝试构建树时,在addnode()函数的“currentNYT->lchild=newNYT;”行执行代码时出现了分段错误 谁能帮我一下吗?这可能是我不知道的一些简单的事情。有一段时间没用C了 //variable and type declarations struct treeElement { unsigned long weight; unsigned short id; char chr; struct treeElem
//variable and type declarations
struct treeElement {
unsigned long weight;
unsigned short id;
char chr;
struct treeElement *lchild, *rchild, *parent;
};
typedef struct treeElement node;
node *root, *currentNYT;
//functions
void initTree() {
root = NULL;
currentNYT = malloc(sizeof(node));
currentNYT = root;
} //initTree
void addNode(char newNodeChr) {
node *newNYT, *newExternal;
newNYT = malloc(sizeof(node));
newNYT->id=maxNodes-idCount; idCount++;
newNYT->chr='\0';
newNYT->weight=0;
newNYT->parent=currentNYT;
newNYT->lchild=newNYT->rchild=NULL;
newExternal = malloc(sizeof(node));
newExternal->id=maxNodes-idCount;
newExternal->chr=newNodeChr;
newExternal->weight=1;
newExternal->parent=currentNYT;
newExternal->lchild=newExternal->rchild=NULL;
currentNYT->lchild = newNYT;
currentNYT->rchild = newExternal;
currentNYT=newNYT;
} //addNode
嗯,您正在将currentNYT设置为NULL。你的意思是:
root = currentNYT;
相反
您可能还需要初始化该节点的元素。哦,也许可以检查一下malloc成功了
这样做可能更清楚
root = malloc(sizeof(node));
if (!root) {
/* panic! */
}
root->.... = whatever; /* for each of the elements of the struct */
currentNYT = root;
看看这个:
root = NULL;
currentNYT = malloc(sizeof(node));
currentNYT = root;
将
root
设置为NULL
,然后将currentNYT
设置为root
。因此currentNYT
总是NULL
以下似乎是第一个错误
currentNYT = malloc(sizeof(node));
currentNYT = root;
可能想要
root = malloc(sizeof(node));
currentNYT = root;
相反,删除currentNYT=root将使我摆脱segfault,但不幸的是,它不能满足我的需要 我想初始化我的树。根目录将为空,子目录为空。currentNYT最初将指向根 addNode()将始终向currentNYT节点添加两个新的子节点。左边的子节点是newNYT,右边的节点是将值作为函数参数发送的节点。addNode()的下一次调用也将执行相同的操作,但两个新节点的父节点将是newNYT,因此currentNYT必须在addNode()的第一次调用后指向newNYT currentNYT将始终指向下一次调用addNode()时将作为父节点的节点
我真的希望有人能帮上忙。你最好把它作为一个新问题重新发布。
root = malloc(sizeof(node));
currentNYT = root;