This is a situation where I have a function that receives the number of rows and columns of a ray and I want to dynamically create it within the function.
#include <stdlib.h>
int **array;
array = malloc(nrows * sizeof(int *));
if(array == NULL)
{
fprintf(stderr, "out of memory\n");
exit or return
}
for(i = 0; i < nrows; i++)
{
array[i] = malloc(ncolumns * sizeof(int));
if(array[i] == NULL)
{
fprintf(stderr, "out of memory\n");
exit or return
}
}
this does not work because in VS 2011开发者_如何学Go, it says that array = malloc(n * sizeof (int *)); void * cannot be assigned to int * How do I fix that?
Visual C++ is a C++ compiler, and C++ requires you to cast void*
s explicitly, unlike C which allows implicit casting of void*
s.
Try
array = (int**)malloc(nrows * sizeof(int *));
However, that's how you would do it in C, and if you decide later to change the data from int
s to some sort of object, the object's constructor wouldn't be called, because you used malloc
. If you want to do it the more C++-ish way, which works for all data types, you would use new
:
int** array = new int*[nrows];
for (int i = 0; i < nrows; ++i)
array[i] = new int[ncolumns];
This way also saves you from having to calculate the object's size with n * sizeof(type)
.
However, if you choose to use malloc
to allocate a block of memory, you must use free
to deallocate it; conversely, if you choose to use new
to allocate a block of memory, you need to use delete
to delete it (Remember to use delete[]
on arrays and plain delete
on non-arrays). Using delete
on a malloc
'd memory block or free
on a new
'd memory block results in undefined behaviour. The reason for this is that malloc
allocates memory on the heap but new
allocates memory on the free-store. They could happen to be the same thing; in fact, some implementations of new
and delete
use malloc
and free
under the hood, but that's compiler-dependent, so don't ever do it.
Note that you can use malloc
and free
in the same program, but that is not recommended because you could easily forget which one allocated a specific block of memory and use the wrong deallocation function on it.
精彩评论