Confusion with pointer to structure in c/c++
c, c++
Solution
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.
Problem
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; } ```