title: Matrix of structs in C
body: <p>How do I make a matrix of structs or a matrix of pointers to structs? The elements in the matrix <code>a</code> should be structs of type <code>Area</code>.</p>
  
  <p>Here is what I've tried so far:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;math.h&gt;
  
  typedef struct {
    char type_toy[20];
    int nr;
    char town[20];
    char direction;
  } Area;
  
  void AllocMatrix(int N, int M, Area** a) {
    int i;
    a = malloc(N * sizeof(Area *));
    for (i = 0; i &lt; N; i++) {
      a[i] = calloc(M, sizeof(Area*));
    }
  }
  
  int main() {
    int N, M;
    Area** a;
    printf("N = ..., M = ...");
    scanf("%d %d", &amp;N, &amp;M);
    AllocMatrix(N, M, a);
  
    for (i = 0; i &lt; N; i++) {
      for (j = 0; j &lt; M; j++) {
        scanf ("%s", &amp;a[i][j].town);
        scanf ("%s", &amp;a[i][j].type_toy);
        scanf ("%d", &amp;a[i][j].nr);
        scanf ("%s", &amp;a[i][j].direction);
      }
    }
    return 0;
  }
  </code></pre>