【发布时间】:2017-04-25 11:23:08
【问题描述】:
我需要像这样递归地打印结构数组中的数据,
index, numberOfChildern, child[0]...child[numberOfChildern-1]
问题是,对于每个孩子,我还需要打印 index, numberOfChildern, child[0]...child[numberOfChildern-1]。
typedef struct node point;
typedef point **pointsList;
结构:
struct node{
int index; //the order in the instance file
int x;//x coord
int y;//y coord
int parent;//parent in tree when added
int numChildern;//has val 0 -- 8 maybe, but doesn't matter the way I wrote it
int *child;
};
每个结构中的所有值都设置正确,这是我开始编写以完成任务的不完整方法。
void printStringOfChildern(pointsList list, point *point, int fileNum){
if(point->numChildern == 0)
return;
//print the index
char index[calcNumberOfDigitsInAInt(point->index)+3];
sprintf(index, "%d", point->index);
strcat(index, ", ");
print(index, fileNum);
//print the number of childern
char chidern[calcNumberOfDigitsInAInt(point->numChildern)+3];
sprintf(chidern, "%d", point->numChildern);
strcat(chidern, ", ");
print(chidern, fileNum);
//print the childern
for(int i=0; i<point->numChildern; i++){
char child[calcNumberOfDigitsInAInt(point->child[i])+3];
//was child[i] now point->child[i]
sprintf(child, "%d", point->child[i]);
strcat(child, ", ");
print(child, fileNum);
//print out other childern and their data if there is any
int numChildern = numberOfChildern(list, point -> index);
if(numChildern > 0){
printStringOfChildern(list, list[point->child[i]], fileNum);
}
}
}
您会注意到上面的代码很糟糕且不完整,但它显示了我的打印功能的使用
下面的 if else 块是我打印到输出的方式,它可以是一个文件或一系列文件的终端。打印功能和 this if else 块已经过测试,并证明可以工作。 inOutType 是一个全局变量,outputFileName 也是如此。 fileIndex 仅在打印到多个文件的情况下使用,并且在打印到多个文件的情况下,无论有多少文件,都会调用此方法。这是打印功能
if(inOutType == 1 || inOutType == 2){
printLineToOutPut(output, outputFileName, inOutType);
}else{
printToAInstanceFile(output, fileIndex);
}
我在编辑中所做的只是更新示例,然后写这个
Output format:
index, numberOfChildern, child[i]. If child[i] has children then index, numberOfChildern, indexOf(child[i]), numberOfChildernOf(child[i]), child[i]OfChild[i].....
方法是这样执行的
for(int j=0; j<maxNumberOfPoints; j++)
printStringOfChildern(listOfListOfPoints[i], listOfListOfPoints[i][j], i);
【问题讨论】:
-
首先了解基础知识,例如
strcat()的工作原理以及sprintf()的不安全性。另外,避免全局变量!并学习调试的重要技能。 -
主要是想看看是否有人会更快地解决它,我现在正在写它。如果您没有像我所做的那样计算字符串大小,则 strcat 和 sprintf 是不安全的。在这种情况下,使用全局变量更简单。我遗漏了 90% 的代码。 @iharob
-
请不要在点
.和箭头->运算符周围使用空格。它们结合得非常紧密,它们周围的空间充其量是非常规的,并且表明代码的作者是新手 C 程序员。 (另外,在英语中,“child”的复数形式是“children”而不是“childern”。) -
你应该真正展示一个简单的例子——也许是一个有 3 个孩子的父母,其中中间的父母有 2 个孙子女。输出应该是什么样子?
-
@Jonathan Leffler 我添加了更新,它现在几乎可以工作了。它打印传递点的孩子,但不打印那个孩子的孩子
标签: c arrays pointers recursion struct