Friday, 15 August 2014

c - Memory allocation for structure extension -


Suppose I have two structures, one of which is extending (below) below the other. What is the right procedure to deal with memory when creating an extended structure from an existing structure? Should the new structure be called again? Can this double the memory allocation, where it should not be?

  typed strip grid {int lines; Int Coles; Int * grid; } Trap; Typingfade strait super grid {grid; Four * assets; Int id; } Super Grid; Fixed grid * new_grid (int rows, int cols) {grid * grid = (grid *) (maulok (grid)); Grid-> Line = rows; Grid-> Cols = cols; Grid-> Grid = (integer *) (coloc (rows * cols, sizeof (int)); } Static Super Grid * new_super_grid (int row, int colals) {/ * What needs to happen here? * / Return (Super Grid *) new_grid (rows, columns); }   

Your structure expansion mechanism is similar to primitive + + To achieve its goal + class derivation system, you must isolate the structure allocation and initialization:

  typedef struct grid {int lines; Int Coles; Int * grid; } Trap; Typingfade strait super grid {grid; Four * assets; Int id; } Super Grid; Fixed grid * init_grid (grid * grid, int rows, int coles) {if (grid) {grid-> Line = rows; Grid-> Cols = cols; Grid-> Grid = (integer *) coloc (rows * cols, sizeof (int)); } Return grid; } Static Grid * New_grid {return init_grid (grid *) malloc (size (grid)), rows, columns;} Stable super grid * init_super_grid (super grid * sg, int rows, int cols, Contact char * property, int id) {if (sg) {init_grid (grid *) sg, rows, cols); sg-> property = strdup (asset); sg-> id = id;} return SG;} Static Super Grid * new_super_grid (Super Grid * SG, Int, Rows, Ent Calls, Const char * Oprti, Int id) {return init_super_grid (Suprgrid *) Molok (Saijhf (super grid)), lines, Coles, property, id); }  

The allottees may fail and may return NULL in case of memory allocation failure. You want them to fail more clearly, as if the program exits error messages through abort Similarly, delete_xxx functions to NULL free and should be ignored as C ++ Delete operator.

For stability, you can call delete_grid and finalize_grid function from finalize_grid to finalize_super_grid . This is not strictly necessary for this simple example, but if you are not allocated to the grid structures (with static or automatic storage or embedded in more complex superstructures) Can prove to be easy.

The C ++ class system of this poor man will immediately show your boundaries, you can consider using C ++ directly.


No comments:

Post a Comment