www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Malloc struct

reply "codenstuff" <nikolapav1985 gmail.com> writes:
I need to create following struct using malloc

struct Map {
int **entries;
int rows;
int cols;
}
Map *map_create(int rows, int cols) {
   Map *that = cast(Map*)malloc(Map.sizeof);
   that.entries = cast(int**)malloc(rows * int.sizeof);
   foreach(row; 0..rows) {
     that.entries[row] = cast(int*)malloc(cols * int.sizeof);
   }
   that.rows = rows;
   that.cols = cols;
   return that;
}

I find that memory is collected when pointer is returned (from 
some of the entries). How do I prevent that? The code should 
behave as in C.
Jul 06 2015
parent Steven Schveighoffer <schveiguy yahoo.com> writes:
On 7/6/15 2:15 PM, codenstuff wrote:
 I need to create following struct using malloc

 struct Map {
 int **entries;
 int rows;
 int cols;
 }
 Map *map_create(int rows, int cols) {
    Map *that = cast(Map*)malloc(Map.sizeof);
    that.entries = cast(int**)malloc(rows * int.sizeof);
(int *).sizeof -Steve
Jul 06 2015