我不明白我的代码中发生了什么......我声明了我可以在两个函数之间使用的全局变量,其中一个函数是递归的。但是我遇到的问题是,每次我的代码退出递归函数时,我在全局变量中的值都会再次设置为零值。虽然它必须包含 EOF 值才能终止 while 循环。
全局变量: int 电流字符;
在这里使用:
int currChar; // <-- GLOBAL VAR
int createStructureRec(FILE *fp, Node *temp){
int currChar = getc(fp); //<-- I WAS STUPID HERE!!!!
if (currChar != EOF ) currChar = charToIndex(currChar);
if(currChar == EOF || currChar == -1){
temp -> numOfOccur++;
if(temp -> numOfOccur == 1){
temp -> numOfSuperWords--;
return 1;
}
else return 0;
}
int returnValue = 0;
if (temp -> children[currChar].children == NULL){
temp -> children[currChar].children = (Node *)calloc(27, sizeof(struct node));
temp -> children[currChar].numOfOccur = 0;
temp -> children[currChar].numOfSuperWords = 0;
temp = &temp -> children[currChar];
returnValue = createStructureRec(fp, temp);
}else{
temp = &temp -> children[currChar];
returnValue = createStructureRec(fp, temp);
}
temp -> numOfSuperWords += returnValue;
return returnValue;
}
所以在这个函数中,每次我的全局变量都得到零值,因此循环永远不会终止。
void createStructure(FILE *fp){
root.numOfOccur = 0;
root.children = (Node *)calloc(27, sizeof(struct node));
currChar = 0;
Node* temp = &root;
while (currChar != EOF)
createStructureRec(fp, temp);
}
请帮忙!
最佳答案
改变:
int createStructureRec(FILE *fp, Node *temp){
int currChar = getc(fp);
到:
int createStructureRec(FILE *fp, Node *temp){
currChar = getc(fp);
您已经声明了一个具有相同名称的局部变量 currChar
并且使用了这个局部变量而不是全局变量。
关于c - 在将它与两个函数一起使用时丢失全局变量的值,其中一个是递归的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25963029/