这是一个使用动态内存的非常标准的应用程序。您将要做的是为初始整数数声明内存,读取直到达到该数,重新分配两倍于原来大小的数组,然后继续读取所有数据。
虽然将整行数据读入缓冲区,然后根据需要解析缓冲区通常是最佳实践,但在这种情况下,fscanf 是专门为处理单个整数值的读取和转换而设计的(以及它会自动使用分隔值的空格)。
(下面使用calloc 将所有元素初始化为0,malloc 在此示例中很好,但在更复杂的情况下,初始化可防止无意中读取未初始化的元素)
这是一个简短的例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXI 64
int main (int argc, char **argv) {
int *array = NULL;
size_t idx = 0, max_idx = 0;
size_t arraysize = MAXI;
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) {
fprintf (stderr, "error: file open failed. '%s'\n", argc > 1 ? argv[1] : "stdin");
return 1;
}
/* allocate initial array */
array = calloc (MAXI, sizeof *array);
/* read values from file */
while (fscanf (fp, "%d", &array[idx]) == 1) {
idx++;
/* realloc if necessary */
if (idx == arraysize) {
int *tmp = realloc (array, arraysize * sizeof *array * 2);
if (!tmp) {
fprintf (stderr, "error: realloc - virtual memory exhausted.\n");
return 1;
}
array = tmp;
memset (array + arraysize, 0, arraysize); /* zero new memory */
arraysize *= 2;
}
}
/* close file */
if (fp != stdin) fclose (fp);
max_idx = idx;
/* print array */
for (idx = 0; idx < max_idx; idx++)
printf (" array[%3zu] : %d\n", idx, array[idx]);
free (array); /* free memory */
return 0;
}
示例数据
$ cat dat/100intspace.txt
27086 29317 32736 3356 12059 13921 9388 25672 19828 25390 -1190 25857 ...
输出
$ ./bin/array_dyn_read_int dat/100intspace.txt
array[ 0] : 27086
array[ 1] : 29317
array[ 2] : 32736
array[ 3] : 3356
array[ 4] : 12059
array[ 5] : 13921
array[ 6] : 9388
array[ 7] : 25672
array[ 8] : 19828
array[ 9] : 25390
array[ 10] : -1190
array[ 11] : 25857
...
验证您的内存使用情况
当您动态分配内存时,您有责任 (1) 跟踪您分配的内容; (2) 保留一个指向起始地址的指针(以便稍后释放它); (3) 在不再需要时释放内存。 valgrind 或类似的内存错误检查器使用简单,应该用于验证您的内存使用情况:
$ valgrind ./bin/array_dyn_read_int dat/100intspace.txt
==7348== Memcheck, a memory error detector
==7348== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==7348== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==7348== Command: ./bin/array_dyn_read_int dat/100intspace.txt
==7348==
array[ 0] : 27086
array[ 1] : 29317
array[ 2] : 32736
array[ 3] : 3356
array[ 4] : 12059
array[ 5] : 13921
array[ 6] : 9388
array[ 7] : 25672
array[ 8] : 19828
array[ 9] : 25390
array[ 10] : -1190
array[ 11] : 25857
....
==7348==
==7348== HEAP SUMMARY:
==7348== in use at exit: 0 bytes in 0 blocks
==7348== total heap usage: 3 allocs, 3 frees, 1,336 bytes allocated
==7348==
==7348== All heap blocks were freed -- no leaks are possible
==7348==
==7348== For counts of detected and suppressed errors, rerun with: -v
==7348== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
如果您有任何问题,请告诉我。