title: Dynamically allocating 2-dimensional array in Struct (in C)
body: <p>I have a structure called container that has two fields: <strong>labels</strong> and <strong>linked_to_containers</strong>; The field labels is designed to be a 2-dimensional array of int, and the field linked_to_containers is designed to be a 2-dimensional array of int pointers. On top of this, I also have an array of <code>struct container</code> that are dynamically created in the initiation program. I have the following code written down, but one thing I'm unsure about is the first <code>malloc</code> I used inside of the function <code>container_init()</code>. As the <code>struct container</code> still does not have its size initialized, is this the right way to do <code>malloc</code> for creating an array of struct container?</p>
  
  <p>Please see my question in my comments in the code, and I will appreciate your feedback.</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  typedef struct container {
      int *labels[2];                  /* two-dimensional array of int */
      int **linked_to_container[2];    /* two-dimensional array of pointers to label */
  } container;
  
  int get_next_container_index(int current_container_index, int max_index)
  {
      if (max_index - current_container_index &gt;= 1)
      {
          return current_container_index + 1;
      }
      else 
          return 0;        /* elements at two ends are linked */
  }
  
  container *allcontainers;   /* an array for all containers */
  
  void container_init(int num_containers, int column_num)
  {
      /* is this right to malloc memory on the array of container when the struct size is still unknown?*/
      allcontainers = (container *) malloc(num_containers * sizeof(container));
  
      int i;
      for (i = 0; i &lt; num_containers; i++)
      {
          container *current_container = &amp;allcontainers[i];
          current_container-&gt;labels[0] = malloc(column_num * sizeof(int));
          current_container-&gt;labels[1] = malloc(column_num * sizeof(int));
  
          current_container-&gt;linked_to_container[0] = malloc(column_num * sizeof(int *));
          current_container-&gt;linked_to_container[1] = malloc(column_num * sizeof(int *));
  
          int j;
          for (j = 0; j &lt; column_num; j++)
          {
              current_container-&gt;labels[0][j] = 0;     /* initialize all labels to 0 */
              current_container-&gt;labels[1][j] = 0;
  
              int next_container = get_next_container_index(i, num_containers - 1);     /* max index in all_containers[] is num_containers-1 */
              current_container-&gt;linked_to_container[0][j] = &amp;(allcontainers[next_container]-&gt;labels[0]);
          }
      }
  </code></pre>