如果您想将未知数量的有序对读入有序对数组,有多种方法可以解决此问题。如评论中所述,如果您可以保证每行始终有 2 个整数,那么读取/将值转换为整数的最简单方法可能是使用 fscanf
(当您在每一行上具有完全相同的数据格式时,我会推荐fscanf 而不是fgets 和sscanf,这是唯一次之一,然后它只是简化示例)
当您要读取的元素数量未知时,基本方案是为一些合理预期的数字对分配内存,然后根据需要分配realloc。由于您正在阅读有序对,因此您可以通过为 pointer-to-array-of-two-int 分配存储空间来简化流程。例如,您的 ordered-pairs 数组 op 声明如下:
int (*op)[2] = NULL;
您可以为 MXLINE 对数分配存储空间:
op = calloc (MXLINE, sizeof *op);
(您可以使用malloc 或calloc 来分配)
在分配初始内存来保存有序对后,您可以使用包含两个十进制转换说明符(例如"%d %d")的格式字符串读取每一行并让fscanf 执行转换。您必须验证 2 转换是否发生,然后将值存储在您的数组中。
保持对您添加的配对数量的持续计数,以便您在达到限制时可以realloc。一个例子如下所示。不要忘记在不再需要时释放所有内存,并通过内存检查器运行您的代码以验证您对动态分配内存的使用。
使用您的数据文件将它们放在一个简短的示例中,您可以执行以下操作。注意:程序将从命令行第一个参数给出的文件中读取(如果没有给出文件名,则默认从stdin):
#include <stdio.h>
#include <stdlib.h>
#define MXLINE 2
int main (int argc, char **argv) {
int i, idx = 0, mxline = MXLINE;
int (*op)[2] = NULL;
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
}
/* allocate/validate initial memory */
if (!(op = calloc (MXLINE, sizeof *op))) {
fprintf (stderr, "error: virtual memory exhausted.\n");
return 1;
}
/* read each ordered pair into 'op' array */
while (fscanf (fp, "%d %d", &op[idx][0], &op[idx][1]) == 2) {
if (++idx == mxline) { /* realloc when limit reached */
void *tmp = realloc (op, sizeof *op * mxline * 2);
if (!tmp) { /* validate reallocation */
fprintf (stderr, "error: realloc failed.\n");
break;
}
op = tmp; /* assign reallocated pointer to op */
mxline *= 2; /* update line allocation limit */
}
}
for (i = 0; i < idx; i++) /* show ordered pairs */
printf ("pair[%3d] %3d : %3d\n", i, op[i][0], op[i][1]);
free (op); /* free allocated memory */
if (fp != stdin) /* close file if not stdin */
fclose (fp);
return 0;
}
使用/输出示例
$ ./bin/array_ptr2array <dat/orderedpairs.txt
pair[ 0] 0 : 1
pair[ 1] 1 : 4
pair[ 2] 9 : 11
pair[ 3] 12 : 45
内存/错误检查
不要忘记验证您是否使用了动态分配的内存,并且您正在释放所有不再需要的内存:
$ valgrind ./bin/array_ptr2array <dat/orderedpairs.txt
==8107== Memcheck, a memory error detector
==8107== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==8107== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==8107== Command: ./bin/array_ptr2array
==8107==
pair[ 0] 0 : 1
pair[ 1] 1 : 4
pair[ 2] 9 : 11
pair[ 3] 12 : 45
==8107==
==8107== HEAP SUMMARY:
==8107== in use at exit: 0 bytes in 0 blocks
==8107== total heap usage: 3 allocs, 3 frees, 112 bytes allocated
==8107==
==8107== All heap blocks were freed -- no leaks are possible
==8107==
==8107== For counts of detected and suppressed errors, rerun with: -v
==8107== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)
(注意: 初始分配是针对 MXLINE (2) 对的。这样做是为了强制重新分配。在现实世界中,您需要尽量减少必须分配内存。因此,如果您认为可以有 20 对左右,请将初始分配设置为 24 或 32 对或您对将拥有的数字的最佳合理猜测(加上一对以防万一) ))
查看一下,如果您有任何问题,请告诉我。