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.
2 Answers 2
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.)
5 Comments
struct) of static storage duration with something that is not a constant expression. Can you post the exact error message with the corresponding line of the source code?malloc at file scope, you must do that in a function.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);
7 Comments
int foo[m][n] (array of array of int) is converted to int (*)[n] (pointer to array of int). Only the first dimension is converted. int (*)[n] and int ** are not compatible.
mallocsome memory to use it as approd[n][3]?