Click to See Complete Forum and Search --> : new to malloc conversion


bitshifter420
February 5th, 2008, 07:55 AM
I can allocate a multi-subscripted array using the new operator like this,
but how do i write it using the malloc function instead.


float (*ptr)[3] = NULL;
int size = 64;

void create(void)
{
ptr = new float [size][3];
}

void destroy(void)
{
if(ptr)
{
delete [] ptr;
ptr = NULL;
}
}

aLiNuSh
February 5th, 2008, 09:06 AM
Are you trying to do something like this? I'm a little confused with your float (*ptr)[3] declaration syntax...

// I want to create a [m][n] matrix in C++
int * createMatrix (int m, int n)
{
int **matrix = new int *[m];

for (int i = 0; i < m; i++)
{
matrix[i] = new int[n];
}
}

// I want to create a [m][n] matrix in C
int * createMatrix (int m, int n)
{
int **matrix = malloc (m * sizeof (int *));
int i;
for (i = 0; i < m; i++)
{
matrix[i] = malloc (n * sizeof (int));
}
}


I didn't write the deleteMatrix () functions but they're pretty easy to implement...

Lindley
February 5th, 2008, 09:15 AM
^You may have to explicitly cast the result of malloc to (int*). Some compilers don't like automatic void* conversion. (Technically I think C allows it, C++ doesn't.)

aLiNuSh
February 5th, 2008, 09:26 AM
^You may have to explicitly cast the result of malloc to (int*). Some compilers don't like automatic void* conversion. (Technically I think C allows it, C++ doesn't.)
As far as I know, C allows this implicit conversion but C++ is a little stricter so if he's using malloc() with C++ (why not use new?) he will need to cast the void pointer to an int pointer.

Lindley
February 5th, 2008, 09:33 AM
(why not use new?)

Sometimes it helps to make explicit the fact that no constructor is being called. It's something you have to be careful with, though.