Faust Faust - 3 months ago 5
C++ Question

Member of class point to member of class

I just started with c++, and i have a problem with pointing to an address of memeber of class.
When i compile there are no errors, but program breaks when I run it.

class vise
{
public:
int h1=10;
int n1=12;
int *x;
int set();
};

class vodv
{
public:
vise *v;
int g;
};

int vise::set()
{
h1=5;
return 0;
}


this line break the program

vodv f;
vise v1;
(f.v)->x=&(v1.n1);

Answer

You are not allocating memory for v, and so when you try to access it:

(f.v)->x = &(v1.n1);
     ^^^
   Dereferences 'v'

v can point to any memory address. Dereferencing it is undefined behavior, which sometimes (it is undefined after all) crashes your program.