单个malloc调用中的二维数组 [英] 2-D array in single malloc call
问题描述
int ** arrayPtr;arrayPtr = malloc(sizeof(int)*行* cols + sizeof(int *)*行);
在上面的代码中,我们试图在单个 malloc
调用中分配2D数组. malloc
占用多个字节,并为该多个字节分配内存,但是在上述情况下, malloc
如何知道它首先必须分配一个指针数组,每个指针都指向一个一维数组?
在这种特殊情况下, malloc
在内部如何工作?
2D数组与指向数组的指针的数组不同.
int ** arrayPtr
没有定义2D数组.二维数组如下所示:
int数组[2] [3]
指向该数组第一个元素的指针将如下所示:
int(* array)[3]
您可以指向一个内存块:
int(* array)[3] = malloc(sizeof(int)* 5 * 3);
请注意如何对其进行索引:
-
array [x]
将扩展为*(array + x)
,因此"x个3个整数的数组向前". -
array [x] [y]
会扩展为*(*(array + x)+ y)
,因此那么y个整数向前".
这里没有立即涉及的指针数组,只有一个连续的内存块.
如果您有一个数组数组(与2D数组不同,通常使用 int ** ptr
和一系列的每行malloc来完成),它将像这样:/p>
-
ptr [x]
将扩展为*(array + x)
,因此"x个指针向前" -
ptr [x] [y]
将扩展为*(*(array + x)+ y)
="y个整数向前".
注意差异.两者都以[x] [y]进行索引,但是它们在内存中的表示方式不同,并且索引的生成方式也不同.
int **arrayPtr;
arrayPtr = malloc(sizeof(int) * rows *cols + sizeof(int *) * rows);
In the above code, we are trying to allocate a 2D array in a single malloc
call.
malloc
takes a number of bytes and allocates memory for that many bytes,
but in the above case, how does malloc
know that first it has to allocate a array of pointers, each of which pointer points to a one-dimensional array?
How does malloc
work internally in this particular case?
2D arrays aren't the same as arrays of pointers to arrays.
int **arrayPtr
doesn't define a 2D array. 2D arrays look like this:
int array[2][3]
And a pointer to the first element of this array would look like:
int (*array)[3]
which you can point to a block of memory:
int (*array)[3] = malloc(sizeof(int)*5*3);
Note how that's indexed:
array[x]
would expand to*(array+x)
, so "x arrays of 3 ints forward".array[x][y]
would expand to*( *(array+x) + y)
, so "then y ints forward".
There's no immediate array of pointers involved here, only one contignous block of memory.
If you'd have an array of arrays (not the same as 2D array, often done using int** ptr
and a series of per-row mallocs), it would go like:
ptr[x]
would expand to*(array+x)
, so "x pointers forward"ptr[x][y]
would expand to*( *(array+x) + y)
= "y ints forward".
Mind the difference. Both are indexed with [x][y], but they are represented in a different way in memory and the indexing happens in a different manner.
这篇关于单个malloc调用中的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!