[英]Confusion with pointer to structure in c/c++
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;
}
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. 您正在创建一个本地对象d
,然后将f
设置为该对象的地址。 Once the function ends, the object goes out of scope and you're left with a dangling pointer. 一旦函数结束,对象就会超出范围而你会留下一个悬空指针。
Your biggest problem is that by the time dh()
returns, d
is no longer in scope. 你最大的问题是,当dh()
返回时, d
不再在范围内。 Instead of ad;
而不是ad;
in dh()
, you need f = new a(); fs=1; fb=2, fh="ffdf";
在dh()
,你需要f = new a(); fs=1; fb=2, fh="ffdf";
f = new a(); fs=1; fb=2, fh="ffdf";
. 。
In test::dh, you assign public pointer f the address of d, which is a local variable. 在test :: dh中,您将公共指针f指定为d的地址,这是一个局部变量。 When g.dh();
当g.dh();
exits, the address of d is no longer valid, which is why the references to f in g.dt();
退出时,d的地址不再有效,这就是为什么在g.dt();
引用f的g.dt();
fail. 失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.