Memory allocation deallocation 2d array

Memory allocation deallocation 2d array

Memory allocation deallocation 2d array

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*/

}

}

Assign memory to 2d array using new :

int **pd ;

pd=new int*[ROW];

for(int i=0; i<ROW; i++)

pd[i]=new int[COL]

Memory allocation deallocation 2d array

Delete a 2d array :

{memory allotted by new}

for (int i = 0; i < n; ++i)

{

delete [] pd[i];

}

delete [] pd;

}

Delete a 2d array :

{memory allotted by malloc}

for(int i = 0; i < N; i++)
{

free(ptr[i]);

}
free(ptr);

Allocate memory to 3d array:

(using malloc)

int dimen1, dimen2, dimen3;

int i,j,k;

double *** array = (double

***)malloc(dimen1*sizeof(double**));

 

for (i = 0; i< dimen1; i++) {

 

array[i] = (double **) malloc(dimen2*sizeof(double

*));

for (j = 0; j < dimen2; j++) {

array[i][j] = (double *)malloc(dimen3*sizeof(double));

}

}

Contiguous memory allotment  to 2-d array :

int **array2 = malloc(nrows * sizeof(int *));
array2[0] = malloc(nrows * ncolumns * sizeof(int)); // Now change pointers
for(i = 1; i < nrows; i++)
array2[i] = array2[0] + i * ncolumns;

Passing 2D array as an argument to function:

void f2(int *aryp, int nrows, int ncolumns)
{

//… array[i][j] is accessed as aryp[i * ncolumns + j] …

}
This function could be called with the array as
f2(&array[0][0], NROWS, NCOLUMNS);

So, number of rows and columns also passed along with array pointer.

Error in Pointer from base to derived arrray

class B {
public:
virtual void gooo(){
cout << “cmg here”;
}
};
class D : public B {
public:
void gooo(){
cout << “working”;}
};

Now initilizing objects like following:

B *b = new D[5];

(b+2)->gooo();

The problem in calling and initializing like above is that pointer belongs to base class but memory allocated is of child class so here it sometime may point to something which is not expected. As a result segmentation fault is seen.

 

Leave a Reply

Your email address will not be published. Required fields are marked *