Search code examples
cstructinitializationmemset

Proper way to initialize nested structs in C


When using nested structures I tend to do something like the following. I would like to know if that's the proper way to initialize structs in this particular case or if there's a better way of doing it.

#include <string.h>
#include <stdlib.h>

typedef struct inner_struct { 
   char *name;
   int account;
} inner;

typedef struct outer_struct {
   int count;
   char *company; 
   inner *my_inner;
} outer;

outer *
initialize_outer (size_t max) {
   outer *out = malloc(sizeof (outer) * max);
   if (out) {
      memset(out, 0, sizeof *out * max);
      out->count = 0;
      out->company = NULL; 
   }   
   return out;
}

inner *
initialize_inner () {
   inner *in = malloc(sizeof (inner));
   if (in) {
      memset(in, 0, sizeof *in);
      in->account = 0;
      in->name = NULL; 
   }   
   return in; 
}

int main(int argc, char *argv[]){
   int i;
   size_t max_out = 20;
   outer *my_out = initialize_outer(max_out);
   for (i = 0; i<max_out;i++) {
      my_out[i].my_inner = initialize_inner();
   }
}

Solution

  • outer *
    initialize_outer (size_t max) {
        outer *out = malloc(sizeof (outer) * max);
        if (out) {
            memset(out, 0, sizeof (outer) * max);
            out->count = 0; // no need assign 0 to 'account' and NULL to 'name' field
            out->company = NULL; // because memset already assigns 0 to it.
        }   
        return out;
    }
    
    inner *
    initialize_inner (size_t max) {
        inner *in = malloc(sizeof (inner) * max);
        if (in) {
            memset(in, 0, sizeof (inner) * max);
            in->account = 0; // no need assign 0 to 'account' and NULL to 'name' field
            in->name = NULL; // because memset already assigns 0 to it.
        }   
        return in; 
    }
    

    Try this...I hope this helps...