title: C, initialize struct without malloc
body: <p>I would avoid the use of malloc to initialize a structure and I'm looking for the best practice for the design a C software using an oo-style (where possible).</p>
  
  <p><strong>Only C99, not C++</strong></p>
  
  <p>First question, what is preferable when use a struct like an object? typedef its pointer or not?</p>
  
  <p>These are my test(all works using gcc compiler):</p>
  
  <p><strong>case 1</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  typedef struct sItem{
      int n;
      char* text;
  } oItem, *Item;
  
  int main(int argc, char** argv) {
      Item i1=(&amp;(oItem){.n=1, .text="A"});
      Item i2=(&amp;(oItem){.n=100, .text="ABC"});
      printf("%d, %s, %d\n", i1-&gt;n, i1-&gt;text, sizeof(*i1)); // 1, "A", 8
      printf("%d, %s, %d\n", i2-&gt;n, i2-&gt;text, sizeof(*i2)); // 1, "ABC", 8
      return (EXIT_SUCCESS);
  }
  </code></pre>
  
  <p>This works, but i think it should not because text is not initialized to contains strings.
  Is this an invalid piece of code?</p>
  
  <p><strong>case 2</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  typedef struct sItem{
      int n;
      char text[5];
  } oItem, *Item;
  
  int main(int argc, char** argv) {
      Item i1=(&amp;(oItem){.n=1, .text="A"});
      Item i2=(&amp;(oItem){.n=100, .text="ABC"});
      printf("%d, %s, %d\n", i1-&gt;n, i1-&gt;text, sizeof(*i1)); // 1, "A", 12
      printf("%d, %s, %d\n", i2-&gt;n, i2-&gt;text, sizeof(*i2)); // 1, "ABC", 12
      return (EXIT_SUCCESS);
  }
  </code></pre>
  
  <p>This works and I think it is correct, is it?</p>
  
  <p><strong>case 3</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  #define Item_new(i, n, s) (&amp;(oItem){0});Item_ctor(i, n, s);
  #define Item_neww(i, x, s) (&amp;(oItem){\
          .n=x,\
          .text=s\
  })
  
  typedef struct sItem{
      int n;
      char text[5];
  } oItem, *Item;
  
  
  void Item_ctor(Item i, int n, char* text){
      i-&gt;n=n;
      strcpy(i-&gt;text, text);
  }
  
  int main(int argc, char** argv) {
      Item i1=Item_new(i1, 10, "ABC");
      Item i2=Item_neww(i2, 10, "ABC");
      printf("%d, %s, %d\n", i1-&gt;n, i1-&gt;text, sizeof(*i1)); // 10, "ABC", 12
      printf("%d, %s, %d\n", i2-&gt;n, i2-&gt;text, sizeof(*i2)); // 10, "ABC", 12
      return (EXIT_SUCCESS);
  }
  </code></pre>
  
  <p>I think this is very nice, but hides the code, and perhaps might be harmful, what do you think?
  I case 3, what is the best choice: macro or constructor function?</p>