首页 > 解决方案 > 程序编译无错误但不执行数组赋值函数C lang

问题描述

该程序编译良好。我用过gcc -Wall,没有显示错误。

但不知何故,该函数storeFreqDrift在其余代码之后没有执行。任何想法为什么?也许指针有问题?在代码的末尾有文件输入(每个数字都在一个新行中)。我想从函数返回数组值。到目前为止一切正常,但现在我被卡住了。

#include <stdio.h>
#include <stdlib.h>

int freqCount;
int calcFreqDrift(const char *file_name, int *result);
int storeFreqDrift(const char *file_name, int tab[freqCount]);

int main() {
    int result = 0;
    freqCount = calcFreqDrift("numbers.txt", &result);
    printf("total number of frequencies is   %d", freqCount);
    int tab[freqCount]; 
    tab[freqCount] = storeFreqDrift("numbers.txt", &tab[freqCount]);
    printf("kolumna nr 3 to %d", tab[3]);
}

int calcFreqDrift(const char *file_name, int *result) {
    FILE *file = fopen("numbers.txt", "r");
    int i = 0;
    int freqCount = 0;  
    if (file == NULL) {
        printf("unable to open file %s", file_name);
    }
    while (fscanf(file, "%d", &i) == 1) {
        freqCount++;
        printf ("%d\n ", i);
        *result += i;
        printf("\n we are at row nr. %d sum of this number and all numbers before is: %d\n", freqCount, *result);
    }
    fclose(file);
    return freqCount; 
}

int storeFreqDrift(const char *file_name, int tab[freqCount]) {
    for (int i = 0; i < freqCount; i++) {
        tab[i] = 5 + tab[i - 1];
    }
    return tab[freqCount];
}

数字.txt

-14
+15
+9
+19
+18
+14
+14
-18
+15
+4
-18
-20
-2
+17
+16
-7
-3
+5
+1
-5
-11
-1
-6
-20
+1
+1
+4
+18
+5
-20
-10
+18
+5
-4
-5
-18
+9
+6
+1
-19
+13
+10
-22
-11
-14
-17
-10
-1

标签: c

解决方案


从第 10 行的 main() 调用 calcFreqDrift() 但在该函数中,在第 32 行 close(file) ,然后从第 13 行的 main() 调用 storeFreqDrift() 并使用要打开的文件名,但 storeFreqDrift()不打开文件也不读取文件。同样在 storeFreqDrift() 中,第一行读取 for(int i=0; i


推荐阅读