c - 程序编译无错误但不执行数组赋值函数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
解决方案
从第 10 行的 main() 调用 calcFreqDrift() 但在该函数中,在第 32 行 close(file) ,然后从第 13 行的 main() 调用 storeFreqDrift() 并使用要打开的文件名,但 storeFreqDrift()不打开文件也不读取文件。同样在 storeFreqDrift() 中,第一行读取 for(int i=0; i
推荐阅读
- c# - 有没有办法使用 msmq 触发器执行我的 wpf 应用程序?
- c++ - 替代使用命名空间作为模板参数
- regex - Sublime Text - 将文本转换为 JSON 格式
- swift - 运行路径搜索路径原因:无法加载捆绑包“MySecondFramework”,因为它已损坏或缺少必要的资源
- ios - 如何为 iOS 指定特定的模拟器?
- reactjs - 对象 Reactjs 中的数组中的换行符
- r - 为什么“foreach”在并行运行时不导出到我的可变对象?
- sql - 尝试基于另一个表获取结果 - WHERE 中不允许使用聚合函数
- docker - 2 个或更多 Redis docker 共享相同数据
- apache-kafka - 如何在没有源的情况下使用 Kafka 通道配置 Flume?