useing realloc() many times
which one of the following is preferable
file=fopen(argv[1],"r开发者_C百科");
arr=(unsigned int *)malloc(4);
while(!feof(file))
{
++arr_size;
arr=(unsigned int *)realloc(arr,arr_size*sizeof(unsigned int)
fscanf(file,"%u\n",&arr[arr_size-1]);
}
fclose(file);
or this
arr=(unsigned int *)malloc(some_size*sizeof(unsigned int));
file=fopen(argv[1],"r");
arr=(unsigned int *)malloc(4);
while(!feof(file))
{
++arr_size;
fscanf(file,"%u\n",&arr[arr_size-1]);
}
fclose(file);
Why not the third way - work out when you open the file how much memory you require?
精彩评论