“I bought this guide a few days ago to prepare for my interview with Oracle. Many of the questions they asked me were from this guide. I found this book absolutely great!”
I prefer this method because it uses less memory allocation calls and the memory is in a contiguous line. I used calloc.. which can easily be swaped out with calloc. Also.. this makes a 2d array of integers but that is easily changed as well.
array=(int**)malloc(x*sizeof(int));
for(i=0;i<y;i++)
array[i]=(int*)malloc(y*sizeof(int));
I prefer this method because it uses less memory allocation calls and the memory is in a contiguous line.
I used calloc.. which can easily be swaped out with calloc.
Also.. this makes a 2d array of integers but that is easily changed as well.
int x = 0, y = 0;
Array = (int **) calloc( Height, sizeof(int *));
*(Array) = (int *) calloc( Width * Height, sizeof(int));
for(y = 0; y < Height; y++)
{
Array[y] = &(Array[0][x]);
x += Width;
}
I used calloc.. which can easily be swaped out with calloc.
OOPS.. that is a typo
should say:
I used calloc.. which can easily be swaped out with malloc.
The first sizeof() should be sizeof(int *), not sizeof(int).
int a[][]=new int[x][y];
int * Allocate(int x, int y)
{
int size = x * y;
int * arr = =(int*)malloc(size*sizeof(int));
return arr;
}
As memory of arrays are allocated continuously, even for multi dimentional arrays.
In C++ to allocate and free memory respectively:
template
T** Allocate(T** arry, int x, int y)
{
arry = new T*[x];
for(int i=0; i
void Allocate(T** arry, int x, int y)
{
for(int i=0; i
In C++ to allocate and free memory respectively:
template<typename T>
T** Allocate(T** arry, int x, int y)
{
arry = new T*[x];
for(int i=0; i<=x; i++)
arry[i] = new T[y];
return arry;
}
template<typename T>
void Allocate(T** arry, int x, int y)
{
for(int i=0; i<=x; i++)
delete [] arry[i];
delete [] arry;
}
sorry the second function is meant to be called “Delete” and not “Allocate”.
Leave an Answer/Comment