在C中的动态2D数组分配 [英] Dynamic 2D Array allocation in C
本文介绍了在C中的动态2D数组分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C中分配动态数组?目前我有一个函数,我写的 malloc2D
,看起来像这样:
How I should allocate dynamic arrays in C? Currently I have a function I wrote called malloc2D
that looks like this:
void* malloc2D(size_t unitSize, uint firstCount, uint secondCount)
{
void** pointer = malloc(sizeof(id) * firstCount);
for (int i =0; i < firstCount; i ++){
pointer[i] = malloc(unitSize * secondCount);
}
return pointer;
}
它工作正常,但我被告知,该存储器单独分配。
It works fine however I have been told that it puts a lot of strain on the memory allocating separately. What is the best or most conventional way to do this?
推荐答案
你可以像这样将数组分配为一个连续的块。假设你想要ints:
You can allocate the array as a contiguous bloc like this. Suppose you want ints:
int (*arr)[secondCount] = malloc( sizeof(int[firstCount][secondCount]) );
你可以隐藏一个宏,它将typename作为一个宏参数,虽然代码很简单足够的,这是不是真的有必要。
You could hide this behind a macro which takes the typename as a macro argument, although the code is simple enough that that is not really necessary.
这篇关于在C中的动态2D数组分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文