title: malloc for struct and pointer in C
body: <p>Suppose I want to define a structure representing length of the vector and its values as:</p>
  
  <pre><code>struct Vector{
      double* x;
      int n;
  };
  </code></pre>
  
  <p>Now, suppose I want to define a vector y and allocate memory for it.</p>
  
  <pre><code>struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector));
  </code></pre>
  
  <p>My search over the internet show that I should allocate the memory for x separately.</p>
  
  <pre><code>y-&gt;x = (double*)malloc(10*sizeof(double));
  </code></pre>
  
  <p>But, it seems that I am allocating the memory for y->x twice, one while allocating memory for y and the other while allocating memory for y->x, and it seems a waste of memory.
  It is very much appreciated if let me know what compiler really do and what would be the right way to 
  initialize both y, and y->x.</p>
  
  <p>Thanks in advance.</p>