title: C, malloc size of
body: <pre><code>typedef struct _lnode{
      struct _lnode *next;
      size_t row;
      size_t column;
      short data;
  }lnode;
  
  typedef struct _matrix{
  
      size_t width;
      size_t height;
      size_t k;
  
      int **data;
  
  }matrix;
  
  matrix* make_matrix(size_t width, size_t height, size_t k){
  
      matrix *m= malloc(sizeof(matrix));
      //matrix *m= malloc(sizeof(*matrix)); DOES NOT WORK
      if(m==NULL) return NULL;
  
      m-&gt;width = width;
      m-&gt;height = height;
  
      /*
      Since m-&gt;data is a int **, it points to int *, 
      so I have to allocate a number of int *-sized objects to store in it.
      */
      m-&gt;data = malloc(sizeof(int *)*height);
      if(m-&gt;data == NULL){
          free(m);
          return NULL;
      }
  
      for(size_t i=0; i &lt; height; i++){
          m-&gt;data[i] = malloc(sizeof(int)*width);
          if(m-&gt;data[i] == NULL){
              for(size_t j = 0; j &lt; i; j++) free(m-&gt;data[j]);
              free(m-&gt;data);
              free(m);
              return 0;
          }
  
          for(size_t j = 0; j &lt; width; j++)
              m-&gt;data[i][j] = 0;
      }
  
      return m;
  }
  
  
  lnode* make_node(size_t row, size_t column, short data){
      lnode *newNode = malloc(sizeof(*newNode));
  
      if(newNode==NULL) return NULL;
  
      newNode-&gt;row = row;
      newNode-&gt;column = column;
      newNode-&gt;data = data;
  
      return newNode;
  }
  </code></pre>
  
  <p>These two functions work fine. In the make_matrix function, I first tried this</p>
  
  <pre><code> matrix *m= malloc(sizeof(*matrix)); 
  </code></pre>
  
  <p>instead of </p>
  
  <pre><code> matrix *m= malloc(sizeof(matrix));
  </code></pre>
  
  <p>Then it only works for the first iteration in the for loop and falls into the if statement</p>
  
  <pre><code>if(m-&gt;data[i] == NULL){
                  for(size_t j = 0; j &lt; i; j++) free(m-&gt;data[j]);
                  free(m-&gt;data);
                  free(m);
                  return 0;
              }
  </code></pre>
  
  <p>I know that sizeof(pointer) will return a size of the pointer. In make_node function I am doing lnode *newNode = malloc(sizeof(*newNode)); and it worked fine. I am trying to do the same thing in make_matrix function. It doesn't work this time...</p>