Allocate two-dimensional array

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

How can I allocate a bi-dimensional array using malloc? This is my current code:

typedef struct object product, *pprod; struct object{     int type;     int quantity;     pprod next; };  pprod t[4][3]; 

Thanks a lot for your help.

回答1:

To allocate memory in such a way that the layout is compatible with a normal two-dimensional array - or array of arrays - you need a pointer to an array of appropriate size,

pprod (*t)[m] = malloc(n * sizeof *t); 

Thus t is a pointer to arrays of m elements of type pprod, and you can simply use it

t[i][j] 

as if it were declared

pprod t[n][m]; 

(if malloc doesn't return NULL).

This allocation allocates a contiguous block of memory, unlike allocating a pprod ** would.

(Note: If m is not a compile-time constant, that requires that the compiler supports variable length arrays, it would not work with MSVC.)



回答2:

For 2D array you should define a pointer like:

typedef struct obj OBJECT; OBJECT **2Dptr = malloc (sizeof(OBJECT*)*rows) for(i=0;i<rows;i++)   2Dptr[i]=malloc(sizeof(OBJECT)*total_objects) //columns 

There are other ways too, you can define array of pointers to your struct object.

if you want object[5][10] you can create 5 pointers to array of 10 objects; 

if you want the memory to be contiguous then you could do

*2Dptr=malloc(sizeof(OBJECT) * rows * cols);  //allocate contiguosly **access_ptr = malloc(sizeof(OBJECT*) * rows); for(i=0;i<row;i++)    access_ptr[i]= 2Dptr+(i*cols); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!