我已经研究这个代码几个小时了,但它总是给我错误,我真的不知道该怎么做。这段代码应该返回一个由 1 和 0 组成的字符串,读取一棵树。我将在这里放置代码和结构。 当我尝试执行它时,它给我段错误,我不知道问题出在哪里。我希望它返回 char* 。
struct info{
int frequency;
char symbole;
}info;
typedef struct info* pinfo;
struct node{
struct info* in;
struct node* right;
struct node* left;
}node;
typedef struct node* pnode;
struct tree{
pnode root;
int frequency;
};
typedef struct tree* ptree;
char * codage(char c, pnode pn){
char cl[]=" ";
char cr[]=" ";
if(pn->in->symbole==c){
return "";
}else{
printf("testtttK\n");
if(pn->left==NULL){
return "3";
}else{
strcpy(cl,strcat("1",codage(c,pn->left)));
strcpy(cr,strcat("0",codage(c,pn->right)));
}
}
char* res;
if (cl[strlen(cl)-1]=="3"){
res=cr;
return res;
}else{
res=cl;
return res;
}
}
char* compress(char* txt, ptree pt){
int i;
char* res="";
for(i=0;i<(int)strlen(txt);i++){
res=strcat(res,codage(txt[i],pt->root));
}
return res;
}
最佳答案
为了扩展 @WeatherVane 在评论中所说的内容,char *res = ""; 为字符串 res 分配 1 个字节(空字符)。当您连接到 res 时,您的写入超出了字符串边界,并最终浪费了数组外部的内存。此时,行为是未定义的,很容易导致段错误。
关于c - 段错误(核心转储)错误 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52727444/