简体   繁体   English

二维数组和动态分配如何工作?

[英]How do 2-D arrays and dynamic allocation work?

So my idea: 所以我的想法是:

A 2-D array is an array of arrays. 二维数组是数组的数组。 If an array is X by Y, then each X points to an array with length Y. Is that part correct? 如果一个数组是X X Y,则每个X指向长度为Y的数组。那部分正确吗? Is that why also when you want to dynamically allocate an array in C you have to say 这就是为什么当您想在C中动态分配数组时也必须说

array=(type **)malloc(X*sizeof(type *)). 

The type * is to tell the compiler that each array index will be a pointer to another array so it should be sufficiently big enough to hold pointers o array? 类型*是告诉编译器每个数组索引将是指向另一个数组的指针,因此它应该足够大以容纳数组指针?

Also why is this loop needed? 又为什么需要这个循环?

for(i =0;i<X;i++)
{
array[i]=(type *)malloc(Y*sizeof(type))
}

Is the cast 是演员

(type *)

needed because so that each index is a pointer to a 1-D array? 是否需要,因为每个索引都是指向一维数组的指针? But this time in the malloc we can just say (type) instead of (type *) because the index won't be holding pointers any more? 但是这次在malloc我们只能说(type)而不是(type *)因为索引不再持有指针了吗?

EDIT 编辑

Oh..so this is just mimicking a 2-d array by having an each index in an 1-d array point to another 1-d array. 哦,所以这只是通过使1-d数组中的每个索引指向另一个1-d数组来模仿2-d数组。 Ok. 好。 In that case is my logic for why each malloc have that specific argument make sense? 在那种情况下,为什么每个malloc都有该特定参数才有意义? The code here is taken from this SO question dynamic allocation/deallocation of 2D & 3D arrays 这里的代码来自于SO问题的2D和3D数组的动态分配/取消分配

Your code doesn't involve an actual 2D array. 您的代码不涉及实际的2D数组。 This is a 2D array: 这是一个二维数组:

int myArray[X][Y];

It involves no pointers. 它不涉及任何指针。

Your code involves a pointer to an array of pointers, which isn't the same thing. 您的代码包含一个指向指针数组的指针,这不是一回事。


Why is this loop needed? 为什么需要此循环?

Because otherwise all of the pointers in your array of pointers don't point at any storage. 因为否则,指针数组中的所有指针都不会指向任何存储。


Is the cast needed? 需要演员吗?

No. 没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM