作为 TheCrow 答案的后续,如果您确实想以一种允许您处理未知数量的结构的方式为每个 heap[i] 分配,那么您可以使用 pointer-to -指向heaparr(例如heaparr **heap;)的指针,然后最初分配一些指针,并在从输入中读取每个结构时为其分配。
该方案很简单。您保留两个计数器变量。一个代表分配的指针数量,第二个代表使用的数量。当使用的指针数量等于分配的数量时,您只需 realloc 更多指针,然后再尝试分配/填充下一个指针。
下面是一个简单的例子,它从stdin 读取数据并期望每一行都包含"key data name"。最初分配了2 指针,并根据需要通过将当前分配的所有指针都填满时分配的当前数量加倍来重新分配指针的数量,例如
#include <stdio.h>
#include <stdlib.h>
/* if you need constants, #define them or use a global enum */
enum { NPTR = 2, MAXNM = 20, MAXC = 128 };
typedef struct {
int key;
float data;
char name[MAXNM];
} heaparr;
int main (void) {
char buf[MAXC] = ""; /* read buffer */
size_t n = 0, /* current struct filled */
nptr = NPTR; /* initial/current number of pointers */
heaparr **heap = NULL; /* pointer-to-pointer to heaparr */
/* allocate/validate nptr to heap */
if (!(heap = malloc (nptr * sizeof *heap))) {
perror ("malloc-heap");
return 1;
}
while (fgets (buf, MAXC, stdin)) { /* read each line */
heaparr tmp = { .key = 0 }; /* tmp struct */
if (sscanf (buf, "%d %f %19[^'\n']", /* parse line/validate */
&tmp.key, &tmp.data, tmp.name) != 3) {
fprintf (stderr, "error: failed conversion line %zu.\n", n);
continue; /* just read next line on conversion failure */
}
if (n == nptr) { /* check if realloc needed */
/* always relloc to a temporary pointer to avoid mem-leak */
void *tmpheap = realloc (heap, nptr * 2 * sizeof *heap);
if (!tmpheap) { /* validate realloc */
perror ("realloc-tmpheap");
break; /* don't exit, original data still valid in heap */
}
heap = tmpheap; /* assign new block to heap */
nptr *= 2; /* update current pointers allocated */
}
if (!(heap[n] = malloc (sizeof *heap[n]))) { /* allocate heap[n] */
perror ("malloc-heap[n]");
break;
}
*heap[n++] = tmp; /* assign tmp to heap[n], increment n */
}
for (size_t i = 0; i < n; i++) { /* output all values */
printf ("%3d %5.1f %s\n", heap[i]->key, heap[i]->data,
heap[i]->name);
free (heap[i]); /* don't forget to free each struct */
}
free (heap); /* don't forget to free pointers */
return 0;
}
(下面读取 4 个结构体的数据需要上面的 realloc)
输入文件示例
$ cat dat/intfloatstr.txt
1 1.1 my
2 2.2 dog
3 3.3 has
4 4.4 fleas
使用/输出示例
$ ./bin/dynallocstruct <dat/intfloatstr.txt
1 1.1 my
2 2.2 dog
3 3.3 has
4 4.4 fleas
内存使用/错误检查
在您编写的任何动态分配内存的代码中,对于分配的任何内存块,您都有 2 个职责:(1)始终保留指向起始地址的指针内存块,因此,(2) 当不再需要它时可以释放。
您必须使用内存错误检查程序来确保您不会尝试访问内存或写入超出/超出分配块的边界,尝试读取或基于未初始化的值进行条件跳转,最后,以确认您释放了已分配的所有内存。
对于 Linux,valgrind 是正常的选择。每个平台都有类似的内存检查器。它们都易于使用,只需通过它运行您的程序即可。
$ valgrind ./bin/dynallocstruct <dat/intfloatstr.txt
==8846== Memcheck, a memory error detector
==8846== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==8846== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==8846== Command: ./bin/dynallocstruct
==8846==
1 1.1 my
2 2.2 dog
3 3.3 has
4 4.4 fleas
==8846==
==8846== HEAP SUMMARY:
==8846== in use at exit: 0 bytes in 0 blocks
==8846== total heap usage: 6 allocs, 6 frees, 160 bytes allocated
==8846==
==8846== All heap blocks were freed -- no leaks are possible
==8846==
==8846== For counts of detected and suppressed errors, rerun with: -v
==8846== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
始终确认您已释放已分配的所有内存并且没有内存错误。