|
-
February 5th, 2008, 08:55 AM
#1
new to malloc conversion
I can allocate a multi-subscripted array using the new operator like this,
but how do i write it using the malloc function instead.
Code:
float (*ptr)[3] = NULL;
int size = 64;
void create(void)
{
ptr = new float [size][3];
}
void destroy(void)
{
if(ptr)
{
delete [] ptr;
ptr = NULL;
}
}
-
February 5th, 2008, 10:06 AM
#2
Re: new to malloc conversion
Are you trying to do something like this? I'm a little confused with your float (*ptr)[3] declaration syntax...
Code:
// 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...
-
February 5th, 2008, 10:15 AM
#3
Re: new to malloc conversion
^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.)
-
February 5th, 2008, 10:26 AM
#4
Re: new to malloc conversion
 Originally Posted by Lindley
^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.
-
February 5th, 2008, 10:33 AM
#5
Re: new to malloc conversion
 Originally Posted by aLiNuSh
(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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|