There are two structures, one nested in the other, and the nested one is dynamic. How is the access to the fields of the nested structure (there is a pointer) and how to properly free up memory?

struct One { G4double A, B; G4int id; }; struct Two { G4int event,part; struct One *Spin=new One[part]; } TwoInc; 
  • 1. Are you sure it compiles? 2. If it is C ++, why structures, not classes? 3. Memory is freed by its owner. If the Two structure is the owner of the One instance, it is responsible for freeing the memory. When it is “right” to free memory, the project architect should know best, that is, you. This is often done in a destructor. - VladD
  • one
    I'll tell you more, it also works correctly, though I can’t suck at the pointer to free up memory ... - glebasta
  • not classes because it is already in class. - glebasta
  • @glebasta: 1. Strange, I do not compile: ideone.com/nVzVlF 2. That this “in class” is not a problem. - VladD
  • I will deal with the vector, or find a way out. Here is a compiled ideone.com/ufsrrx - glebasta

1 answer 1

@glebasta , I don’t know why it took so hard (and where to insert it in order to compile), but

  delete [] TwoInc.Spin; // delete [] p->Spin; для Two *p; 

should work.

Why not make it any easier?

  struct Two { int event,part; struct One *Spin; }; ... struct Two TwoInc; TwoInc.part = 10; // инициализируете нужным значением TwoInc.Spin = new One[TwoInc.part]; 

or in function

  struct Two *ini_foo (struct Two *p, int inival) { p->part = inival; p->Spin = new One[inival]; return p; } 

simple and clear.

  • This is another thing, tomorrow I'll try. The fact is that this is the date of the minin, there are events that are represented by a certain format and I would like to process everything beautifully. There was an idea. However, only this. That's the same way through the delete ... probably a dump in another place crashes. I tried the first option, only more perverted, mb such a ride better. But the 2nd option is more interesting. Thank you very much !! - glebasta
  • one
    Thank you (I did everything right). It turns out the dump was in another place. But you gave me an idea of ​​how to improve the code. !! Honor and praise! : D - glebasta