mercredi 4 mars 2015

C++ how to allocate memory to a pointer of a struct which is member of another second struct?


This is the code:



# include<iostream>
#include<stdio.h>
using namespace std;
struct hub
{
int info;
int info2;
};
struct hub2
{
hub *p;
};
int main()
{
hub *pi;
pi = new hub; // allocate memory for pi
pi->info = 30;
pi->info2 = 45;
cout<<pi->info<<" "<<pi->info2; // shows 30 and 45
hub2 obj; // declare a hub2 data type
obj.p = new hub; // allocate memory for obj.p
obj.p = pi; // now obj.p should be identical to what pi points to right?
cout<<"\n"<<obj.p->info<<" "<<obj.p->info2; // This will show 30 and 45
cout<<endl;
delete pi;
cout<<"\n"<<obj.p->info<<" "<<obj.p->info2;//This shows random numbers,why ???
}


Why doesn't obj.p allocate memory after I delete the memory allocated for pi pointer? I really need a solution to this.I have to finish a very important project and I am stuck here with at this memory allocating part :(




Aucun commentaire:

Enregistrer un commentaire