Reputation: 3064
I'm trying to remove some confusion with pointer to structures which are used as members in class. I wrote following code, but even though the program compiles it crashes. Could you please say what I'm doing wrong in the following code?
#include<stdio.h>
#include<string.h>
struct a{
int s;
int b;
char*h;
};
class test
{
public:
a * f;
void dh();
void dt();
};
void test::dh()
{
a d;
d.s=1;
d.b=2;
d.h="ffdf";
f=&d;
}
void test::dt()
{
printf("%s %d %d",f->h,f->b,f->s);
}
int main()
{
test g;
g.dh();
g.dt();
return 0;
}
Upvotes: 3
Views: 301
Reputation: 1758
In test::dh, you assign public pointer f the address of d, which is a local variable. When g.dh();
exits, the address of d is no longer valid, which is why the references to f in g.dt();
fail.
Upvotes: 2
Reputation: 27343
Your biggest problem is that by the time dh()
returns, d
is no longer in scope. Instead of a d;
in dh()
, you need f = new a(); f.s=1; f.b=2, f.h="ffdf";
.
Upvotes: 4
Reputation: 61910
void test::dh()
{
a d; <--
d.s=1;
d.b=2;
d.h="ffdf";
f=&d; <--
}
You're creating a local object, d
, and then setting f
to the address of this object. Once the function ends, the object goes out of scope and you're left with a dangling pointer.
Upvotes: 8