void Huffmancode(HTNode ht[], char *hc[], int n){ char *code = (char *)malloc(n * sizeof(char)); code[n-1] = '\0'; for (int i = 0; i < n; i++) { int p = i; int k = n-1; while (ht[p].parent != -1) { int x = ht[p].parent; if (ht[x].lchild == p) { code[--k] = '0'; } else { code[--k] = '1'; } p = x; } hc[i] = (char *)malloc((n-k) * sizeof(char)); strcpy(hc[i], &code[k]); } free(code); }有什么错误
时间: 2024-02-14 14:12:53 浏览: 20
这段代码的错误在于,对于根节点的处理有误。当根节点的 parent 值为 -1 时,应该跳出循环,而不是继续进行下去。另外,在分配内存时,应该加上检查是否分配成功的判断。修改后的代码如下:
```
void Huffmancode(HTNode ht[], char *hc[], int n){
char *code = (char *)malloc(n * sizeof(char));
code[n-1] = '\0';
for (int i = 0; i < n; i++) {
int p = i;
int k = n-1;
while (ht[p].parent != -1) {
int x = ht[p].parent;
if (ht[x].lchild == p) {
code[--k] = '0';
} else {
code[--k] = '1';
}
p = x;
if (p == 0) // 根节点的 parent 值为 -1,需要特别处理
break;
}
hc[i] = (char *)malloc((n-k) * sizeof(char));
if (hc[i] == NULL) {
printf("内存分配失败\n");
exit(1);
}
strcpy(hc[i], &code[k]);
}
free(code);
}
```