Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C:sprintf和递归_C_Recursion_Segmentation Fault_Printf - Fatal编程技术网

C:sprintf和递归

C:sprintf和递归,c,recursion,segmentation-fault,printf,C,Recursion,Segmentation Fault,Printf,在C语言中,是否可以在sprintf函数中使用递归?由于某些原因,我在执行此操作时会出现分段错误: inline char *TreeNode_toString(const TreeNode *node) { char *out; if(TreeNode_isExternal(node)) // If the node has no children... { sprintf(out, "%s:%.2f", node->name, node->distance)

在C语言中,是否可以在sprintf函数中使用递归?由于某些原因,我在执行此操作时会出现分段错误:

inline char *TreeNode_toString(const TreeNode *node)
{
  char *out;

  if(TreeNode_isExternal(node)) // If the node has no children...
  {
    sprintf(out, "%s:%.2f", node->name, node->distance);
  }
  else // The node is strictly binary, so it will have two non-null children
  {
    char *l = TreeNode_toString(node->l); // l = left child
    char *r = TreeNode_toString(node->r); // r = right child
    sprintf(out, "(%s,%s):%.2f", l, r, node->distance);
  }

  return out;
}

获取段是因为
out
未初始化,而不是因为递归。你应该为它分配一些内存,例如

inline char *TreeNode_toString(const TreeNode *node)
{
  char *out = malloc(4096);  // <-- allocate

  ...

    char *l = TreeNode_toString(node->l);
    char *r = TreeNode_toString(node->r);
    snprintf(out, 4096, "(%s,%s):%.2f", l, r, node->distance);
    // ^-- please use snprintf to avoid buffer overflow, thanks.
    free(l);    // <-- remember to free
    free(r);    // <-- remember to free
  }

  return out;
}
inline char*TreeNode\u toString(const TreeNode*node)
{
char*out=malloc(4096);//l);
char*r=TreeNode_toString(节点->r);
snprintf(输出,4096,“(%s,%s):%.2f”,l,r,节点->距离);
//^--请使用snprintf避免缓冲区溢出,谢谢。

免费(l);//您没有为
out
分配任何内存,因此您正在写入一个随机内存位置。该算法在这方面似乎有点不稳定-您如何知道为
out
分配多少空间-您知道树上的一些大小界限吗?

发布的代码具有未定义的行为。除了递归之外,您是莹:

char * out;
sprintf(out, "%s:%.2f", node->name, node->distance);
换句话说,您试图输出到未初始化的指针,这是未定义的行为,因此没有意义


如果您想问,我是否可以在递归函数中使用sprintf向缓冲区添加信息,答案可能是,但并不容易。您必须在每次递归调用之前维护一个缓冲区,并为每次调用都将更新的缓冲区维护一个索引。

您的意思是分配未初始化-out的声明值并不重要,只是s一些内存空间哦…谢谢你的回答。嗯…我理解这个问题(我以为sprintf负责分配内存)…但我不知道如何解决它。在Java中,它只是公共字符串toString(){if(isExternal())return name+“:“+distance;else return”(“+l.toString()+”:“+r.toString+”);}