NUO*_*NUO 0 c arrays malloc file
我有一个存储整数序列的文件.总的整数是未知的,所以如果我从文件中读取一个整数,我继续使用malloc()来应用新的内存.我不知道我是否可以继续询问内存并在数组末尾添加它们.Xcode一直警告我malloc()行中的'EXC_BAD_EXCESS'.如果我继续从文件中读取整数,我怎么能这样做?
int main()
{
//1.read from file
int *a = NULL;
int size=0;
//char ch;
FILE *in;
//open file
if ( (in=fopen("/Users/NUO/Desktop/in.text","r")) == NULL){
printf("cannot open input file\n");
exit(0); //if file open fail, stop the program
}
while( ! feof(in) ){
a = (int *)malloc(sizeof(int));
fscanf(in,"%d", &a[size] );;
printf("a[i]=%d\n",a[size]);
size++;
}
fclose(in);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
malloc()像这样反复调用并不能达到您的想象.每次malloc(sizeof(int))调用时,它都会分配一个单独的新内存块,该内存块仅对一个整数足够大.写入a[size]最终会为超过第一个值的每个值写下该数组的结尾.
你想要的是这个realloc()功能,例如
a = realloc(a, sizeof(int) * (size + 1));
if (a == NULL) { ... handle error ... }
Run Code Online (Sandbox Code Playgroud)
重新编写代码size实际上是数组的大小,而不是它的最后一个索引,这将有助于简化此代码,但这既不是在这里也不是在那里.