在 C 中为二维数组分配内存的最佳方法? [英] Best way to allocate memory to a two-dimensional array in C?
问题描述
在C
中为二维数组
分配内存的最佳方法是什么,从两个角度来看:memory-management
和速度
?
What is the best way to allocate memory to a two-d array
in C
,from both the perspectives : memory-management
and speed
?
另外,二维数组
(并为其分配内存)或双指针
哪个更好用?有人能详细解释一下,里面发生了什么,为什么一种方法比另一种更好?
Also, which is better to use, a two-d array
(and allocate memory to it) or a double pointer
? Can someone explain in detail,what happens inside,why a method is better than the other one ?
推荐答案
为了获得最佳性能和最佳可读性,此类数组应始终分配为连续的内存块:
To get best performance and best readability, such arrays should always be allocated as a contiguous chunk of memory:
type (*array) [X][Y] = malloc( sizeof(type[X][Y]) );
你应该避免这种情况:
// BAD METHOD, not a real array
type** lookup_table = malloc( X*sizeof(type*) );
for(size_t i=0; i<Y; i++)
{
lookup_table[i] = malloc( Y*sizeof(type) );
}
前者更快,原因有很多.它被分配在一个连续的内存块中,而不是在整个堆中分段.分段版本会阻止所有形式的代码优化和有效的片上数据缓存使用,而且实际分配也慢得多.
The former is faster for many reasons. It is allocated in a contiguous chunk of memory and not segmented all over the heap. Segmented versions block all forms of code optimizations and efficient on-chip data cache use, plus the actual allocation is also much slower.
上面的坏"版本有一个优点,那就是当您希望单个维度具有可变长度时,例如制作字符串查找表时.然后你必须使用那个表格.但是如果你想要一个真正的二维数组,永远没有理由不使用前者.
The "bad" version above has one advantage though, and that is when you want individual dimensions to have variable length, such as when making a look-up table for strings. Then you have to use that form. But if you want a real 2D array, there is never a reason not to use the former.
注意第一个版本通常写成
Note that the first version is usually written as
type (*array) [Y] = malloc( sizeof(type[X][Y]) );
为了更方便的使用:array[i][j]
,而不是可读性较差的(*array)[i][j]
.
to allow more convenient use: array[i][j]
, rather than the less readable (*array)[i][j]
.
这篇关于在 C 中为二维数组分配内存的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!