简体   繁体   English

C ++如何将内存分配给结构的指针,该结构是另一个第二结构的成员?

[英]C++ how to allocate memory to a pointer of a struct which is member of another second struct?

This is the code: 这是代码:

# include<iostream>
#include<stdio.h>
using namespace std;
    struct hub
    {
        int info;
        int info2;
    };
    struct hub2
    {
        hub *p;
    };
    int main()
    {
        hub *pi;
        pi = new hub; // allocate memory for pi
        pi->info = 30;
        pi->info2 = 45;
        cout<<pi->info<<" "<<pi->info2; // shows 30 and 45
        hub2 obj; // declare a hub2 data type
        obj.p = new hub; // allocate memory for obj.p
        obj.p = pi; // now obj.p should be identical to what pi points to right?
        cout<<"\n"<<obj.p->info<<" "<<obj.p->info2; // This will show 30 and 45
        cout<<endl;
        delete pi;
        cout<<"\n"<<obj.p->info<<" "<<obj.p->info2;//This shows random numbers,why ???
    }

Why doesn't obj.p allocate memory after I delete the memory allocated for pi pointer? 为什么obj.p在删除为pi指针分配的内存后没有分配内存? I really need a solution to this.I have to finish a very important project and I am stuck here with at this memory allocating part :( 我真的需要一个解决方案。我必须完成一个非常重要的项目,我被困在这里内存分配部分:(

obj.p = pi; // now obj.p should be identical to what pi points to right?

Yes, both pointers are now equal. 是的,两个指针现在都是平等的。 As a consequence, delete pi is equivalent to delete obj.p . 因此, delete pi等同于delete obj.p Once this is done, the statement 完成后,声明

cout<<"\n"<<obj.p->info<<" "<<obj.p->info2;//This shows random numbers,why ???

tries to access the memory which has just been freed. 尝试访问刚刚释放的内存。 This results in undefined behavior. 这导致未定义的行为。

As a side note, be careful here: 作为旁注,请注意:

obj.p = new hub; // allocate memory for obj.p
obj.p = pi;

The second statement overwrites the pointer to the memory allocated by new hub . 第二个语句将指针覆盖new hub分配的内存。 After that, such memory is no longer accessible, nor can be freed. 在那之后,这样的内存不再可访问,也不能被释放。 This is a memory leak. 这是内存泄漏。

obj.p = new hub; obj.p =新枢纽; // Not necessary ,you can directly write obj.p = pi //没必要,你可以直接写obj.p = pi

delete pi; 删除pi; //After this instruction, pi is free (BUT NOT AUTOMATICALLY TO NULL ) pi points now to a "trash" , it's why you see random number. //在这个指令之后,pi是免费的(但不是自动为空)pi现在指向“垃圾”,这就是你看到随机数的原因。
So you have to reallocate it again . 所以你必须重新分配它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM