///结果值似乎没有存储在tab []数组中。循环完成后,数组为空。 我打算将其作为动态数组,这样就无需声明数组的特定大小。示例文本文件输入位于代码的末尾。实际的文本输入大约有1000行。帮忙了。谢谢//
#include <stdio.h>
#include <stdlib.h>
void read_ints(const char* file_name, int *result);
int main()
{
int result =0;
read_ints("numbers.txt", &result);
}
void read_ints (const char* file_name, int *result)
{
FILE* file = fopen ("numbers.txt", "r");
int i = 0;
int n=0; //row number//
int m;
int tab[m]; //array//
if (file == NULL)
{
printf("unable to open file %s", file_name);
}
while ( fscanf (file, "%d", &i) ==1)
{
n++;
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", n, *result);
tab[n]==*result;
}
printf("\nnumber from row number one is ... : %d\n", tab[1]); //this does not work properly //
fclose (file);
}
numbers.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
答案 0 :(得分:1)
int m;
int tab[m];
这是未定义的行为。一个不错的编译器对此有warned you的信息。始终在您运行的所有编译中启用所有警告,并将所有警告视为错误。
没有自动增长的数组或可以容纳任意数量元素的数组之类的东西。您可以尽早决定大小并坚持使用,或者使用动态数组(查找它)并明确和手动调整大小根据需要。