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...)?
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);
Last edited by sand_man; 05-08-2005 at 09:15 AM.
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.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
No they do not have to be constants.