我应该如何在 C 中分配动态数组?目前我有一个我写的函数叫做malloc2D
看起来像这样:
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;
}
它工作得很好,但有人告诉我,它给单独的内存分配带来了很大的压力。最好或最传统的方法是什么?
您可以一次分配整个块:
int ** foo;
foo = malloc(sizeof(int*) * firstCount);
foo[0] = malloc(sizeof(int) * firstCount * secondCount);
for (int i=1; i<firstCount; i++)
{
foo[i] = foo[0] + i * secondCount;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)