I need to dynamicly allocate a 2 dimensional array in a function.
The parameters that are passed to the function are the columns and rows of the matrix.(Do i use malloc, calloc, new...)?
Printable View
I need to dynamicly allocate a 2 dimensional array in a function.
The parameters that are passed to the function are the columns and rows of the matrix.(Do i use malloc, calloc, new...)?
use malloc
calloc sets the memory to NULL and new/delete is used in C++
example:
Code:#define X 10
#define Y 5
/* allocate */
int i;
*temp = malloc(sizeof(int*) * X);
for(i=0;i<X;i++){
temp[i] = malloc(sizeof(int) * Y);
}
/* delete */
for(i=0;i<X;i++){
free(temp[i]);
}
free(temp);
Do I have to define constants?
Can I use the parameters that are passed to the function to declare the size?
Just search the board - dynamic 2D allocation is a common question - there are plenty of examples to be found.
No they do not have to be constants.