我有一些代码可以创建一个新结构并为结构数组分配一些空间。最初,我为数组上的 1 个结构分配空间:
static int datasetCount = 0;
int datasetgroup_new(DatasetGroup *dg char *id){
dg->id = id;
// Allocate space for a single dataset to start with
dg->datasets = (Dataset *) malloc(sizeof(Dataset));
return 0;
}
然后我有一个函数可以将另一个结构(“数据集”)添加到包含数组的结构中。在函数结束时,我重新分配数组以提供另一个空间:
void datasetgroup_add(DatasetGroup *dg, string filePath){
// Create the dataset
Dataset ds;
dataset_new(&ds, filePath);
// Copy the dataset to the dataset array
dg->datasets[datasetCount] = ds;
// Increment the dataset counter
datasetCount++;
//Grow the array
dg->datasets = (Dataset *)realloc(dg->datasets, sizeof(Dataset) * (datasetCount + 1));
}
我一直在阅读暗示在现代 C 中你不需要做这样的事情的东西。 我可能是错的...那么更现代/更正确的方法是这样做吗?
编辑:
抱歉,我没有使用 C++ 类型,我已经为 string
创建了一个 typedef:
typedef char* string;
最佳答案
如前所述here在现代 C (C11) 标准中没有这方面的内容,但您可以使用像 Glib 这样的库。为了更容易进行内存管理,或者您可以使用它的数据结构,如 array .
如果您使用 visual studio,您可能会在其中找到一些非标准函数。
为了在 linux 中更加具体,这些函数只是 brk()
系统调用的包装器,它们都在用户空间中进行内存管理,它们的速度和效率取决于它们的算法,例如 GNU C 库在堆中获得一些空间,然后为您管理它,这样您的所有 realloc()
调用都不会结束到 brk()
系统调用中,所以不用担心自己他们的效率如此之高。你可以使用 valgrind以便查看您的内存分析。
关于C现代数组分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29824033/