开发者

useing realloc() many times

开发者 https://www.devze.com 2023-03-29 13:19 出处:网络
which one of the following is preferable file=fopen(argv[1],\"r开发者_C百科\"); arr=(unsigned int *)malloc(4);

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消