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.
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.
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.)
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);