在C中将内存分配给二维数组的最佳方法? [英] Best way to allocate memory to a two-dimensional array in C?
问题描述
从memory-management
和speed
的两个角度来看,为C
中的two-d array
分配内存的最佳方法是什么?
What is the best way to allocate memory to a two-d array
in C
,from both the perspectives : memory-management
and speed
?
还更好地使用two-d array
(并为其分配内存)还是double pointer
?有人可以详细解释一下,里面发生了什么,为什么一种方法比另一种更好?
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.
尽管上面的坏"版本有一个优点,那就是当您希望各个尺寸具有可变长度时,例如在为字符串创建查找表时.然后,您必须使用该表格.但是,如果您想要一个真正的2D数组,则没有理由不使用前者.
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屋!