c - 在将它与两个函数一起使用时丢失全局变量的值,其中一个是递归的

标签 c

我不明白我的代码中发生了什么......我声明了我可以在两个函数之间使用的全局变量,其中一个函数是递归的。但是我遇到的问题是,每次我的代码退出递归函数时,我在全局变量中的值都会再次设置为零值。虽然它必须包含 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/

相关文章:

c - 优化MEX文件以加速大型多维数组的乘法(代码瓶颈)

c - 我需要编写一个 C 程序,将两个 100 多个数字相加?

c - 提升为 unsigned 是在结果上还是在每个操作数上完成?

c - 重载 free() 所以我的程序使用我的而不是系统的

c - SB_THUMBTRACK 不重复发送

c - C语言中如何初始化寄存器unsigned long

c - 优化重写以下C代码

c++ - 无法理解 gadgetfs 中的部分代码

c - wait() 和 exit() 调用的错误输出

c - 如何使用 Wininet 向服务器发送二进制 (.zip) 文件