【发布时间】:2014-06-21 04:33:38
【问题描述】:
我一直在试图打破我的 C 编程技能,但我遇到了一个我似乎无法弄清楚的错误。该程序读入由换行符分隔的整数列表。这一点发生在 read_integer_file 中......我通过那里的输入没有问题。当我将数据通过 out 传回 main 时,我遇到了问题。
#include <stdlib.h>
#include <stdio.h>
int read_integer_file(char* filename, int* out)
{
FILE* file;
file = fopen(filename, "r");
/* check if the file open was successful */
if(file == NULL)
{
return 0;
}
int num_lines = 0;
/* first check how many lines there are in the file */
while(!feof(file))
{
fscanf(file, "%i\n");
num_lines++;
}
/* seek to the beginning of the file*/
rewind(file);
out = malloc(sizeof(int)*num_lines);
if(out == NULL)
return 0;
int inp = 0;
int i = 0;
while(!feof(file))
{
fscanf(file, "%i\n", &inp);
out[i] = inp;
printf("%i\n", out[i]); /* <---- Prints fine here! */
i++;
}
return num_lines;
}
int main(int argc, char** argv)
{
if(argc < 2)
{
printf("Not enough arguments!");
return -1;
}
/* get the input filename from the command line */
char* array_filename = argv[1];
int* numbers = NULL;
int number_count = read_integer_file(array_filename, numbers);
for(int i = 0; i < number_count; i++)
{
/* Segfault HERE */
printf("%i\n", numbers[i]);
}
}
【问题讨论】:
-
您确定要让函数的返回类型为
int*吗? -
@500-InternalServerError 我确定我没有!更正了,这不在我的代码中,这是我在搞乱其他东西时留下的。
-
另外,C 不允许在 for (In the main) 中声明变量
-
我知道,我在 GCC 中特意开启了 -std=c99 作为选项
标签: c segmentation-fault