Wednesday, 27 January 2010

Memory Allocation example for Double Pointer of a class

The following program should be self explanatory:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to demonstrate memory allocation to double pointers
#include<iostream>

using namespace
std;

//Class named NewClass
class NewClass
{

public
:
int
a;
int
* b;
void
* c;
};


//List Structure containing multiple NewClass objects
struct NewClassList
{

int
numOfObjects;
NewClass** Objects;
};


int
main()
{

//Create NewClassList with 4 objects with following values:
//1, 10, 100; 2, 20; 200; 3, 30, 300; 4, 40, 400;
NewClassList someList;
someList.numOfObjects = 4;
//someList.Objects = new NewClass*; //1. Common mistake in allocating memory
someList.Objects = new NewClass*[someList.numOfObjects];

someList.Objects[0] = new NewClass;
someList.Objects[0]->a = 1;
someList.Objects[0]->b = new int(10);
someList.Objects[0]->c = (void*) new int(100);

someList.Objects[1] = new NewClass;
someList.Objects[1]->a = 2;
someList.Objects[1]->b = new int(20);
someList.Objects[1]->c = (void*) new int(200);

someList.Objects[2] = new NewClass;
someList.Objects[2]->a = 3;
someList.Objects[2]->b = new int(30);
someList.Objects[2]->c = (void*) new int(300);

someList.Objects[3] = new NewClass;
someList.Objects[3]->a = 4;
someList.Objects[3]->b = new int(40);
someList.Objects[3]->c = (void*) new int(400);

//Printing the outputs
for(int i = 0; i < someList.numOfObjects; i++)
{

cout<<"Iteration = "<<i;
cout<<": a = "<<someList.Objects[i]->a;
cout<<": b = "<<*(someList.Objects[i]->b);
cout<<": c = "<<*((int*)someList.Objects[i]->c)<<endl;
}


//Clear all the memory allocation
for(int i = 0; i < someList.numOfObjects; i++)
{

delete
someList.Objects[i]->b;
delete
someList.Objects[i]->c;
delete
someList.Objects[i];
}

delete
[] someList.Objects;
return
0;
}





The output is as follows:

2 comments:

  1. This was very good example. Do you have more pointers examples? I have found few pointers examples Do you know more websites which can explain pointers step by step?

    ReplyDelete
  2. Example was very useful. Thanks!

    ReplyDelete