Confusion with a pointer to a structure in c / C ++

I am trying to remove some confusion with a pointer to structures that are used as members of a class. I wrote the following code, but even though the program compiles its failure. Could you tell me what I am 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;
}
+3
source share
3 answers
void test::dh()
{
    a d; <--
    d.s=1;
    d.b=2;
    d.h="ffdf";
    f=&d; <--
}

You create a local object d, and then set it fto the address of this object. As soon as the function ends, the object goes out of scope and you are left with a dangling pointer.

+8
source

The biggest problem is that by the time you return it is dh() dno longer in scope. Instead, a d;in the dh()you need f = new a(); f.s=1; f.b=2, f.h="ffdf";.

+4

In the test :: dh, a public pointer f is assigned to address d, which is a local variable. When g.dh();completed, address d is no longer valid, so references to f in g.dt();fail.

+2
source

All Articles