gpt4 book ai didi

c - 尝试打印到文件时 C 中出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:24:21 25 4
gpt4 key购买 nike

提供的二叉树类型是:

struct noeud_s;

typedef struct noeud_s noeud;

typedef noeud* arbre;

struct noeud_s{
char* valeur;
arbre gauche;
arbre droit;
};

我创建的 2 个函数是:

void create_dot(arbre racine)
{
FILE *f;
char file_name[100];
printf ("Nom du fichier a creer (Ajouter .dot a la fin): ");
scanf ("%s", file_name);
printf("Name: %s\n", file_name);
printf ("Creation du fichier dot\n");
f = fopen(file_name, "w");
if (f == NULL)
{
printf("NULL\n");
}
fprintf(f, "digigraph tree {\n");
write_to_dot(f, racine);
fprintf(f, "}");
fclose(f);
}

void write_to_dot(FILE *f, arbre racine)
{
if (racine == NULL)
{
return;
}
if (racine != NULL)
{
fprintf(f, "%s -> %s [label = \"non\"]\n", racine -> valeur, racine -> gauche -> valeur);
fprintf(f, "%s -> %s [label = \"oui\"]\n", racine -> valeur, racine -> droit -> valeur);
write_to_dot(f, racine -> gauche);
write_to_dot(f, racine -> droit);
}
return;
}

就调试而言,我推断我的段错误发生在 write_to_dot 函数内部。但是因为我不能正确处理 gdb,我希望你能帮我找到我的段错误并解释它。

最佳答案

代码正在打印出一个二叉树。没有代码显示节点是如何构造的,但在典型的二叉树中,叶节点有 NULL左右子节点(或者说 gauchedroit)。

函数write_to_dot将在第一个叶节点处失败(如果不在中间分支节点的空侧),因为 racine->gaucheracine->droit将是 NULL , 但它们仍然被取消引用 - racine->gauche->valeur没有任何检查。

虽然我没有所有的代码,但至少测试这个条件可以解决其中一个问题:

void write_to_dot ( FILE *f, arbre racine )
{
if ( racine != NULL )
{
if (racine->gauche != NULL)
fprintf ( f, "%s -> %s [label = \"non\"]\n", racine->valeur, racine->gauche->valeur );
else
fprintf ( f, "%s -> NULL [label = \"non\"]\n", racine->valeur );

if (racine->droit != NULL)
fprintf ( f, "%s -> %s [label = \"oui\"]\n", racine->valeur, racine->droit->valeur );
else
fprintf ( f, "%s -> NULL [label = \"oui\"]\n", racine->valeur );

write_to_dot ( f, racine->gauche );
write_to_dot ( f, racine->droit );
}
}

关于c - 尝试打印到文件时 C 中出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53422242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com