Reputation: 11
#include <iostream>
#include <string>
#include <list>
#include <conio.h>
using namespace std;
class people
{
public:
people* p;
int x;
people();
};
people::people()
{
p = NULL;
}
void main()
{
people jax;
jax.p->x = 1;
}
i got this error
Unhandled exception at 0x00361419 in classarray.exe: 0xC0000005: Access violation writing location 0x00000004.
in this line
jax.p->x = 1;
help me pls !
Upvotes: 1
Views: 171
Reputation: 399
Other way is to implement special function for inner pointer initialization:
void people::init_p()
{
if(!p) p = new people();
}
Upvotes: 1
Reputation: 7705
you need to reserve memory for people:
void main()
{
people jax;
jax.p=new people;
jax.p->x = 1;
...
delete jax.p;
}
EDIT: in the end you need to free your memory, or your will have a memory leak.
Upvotes: 2