title: Returning a structure array using pointers
body: <pre><code>    typedef struct unit_class_struct {
          char *name;
      } person;
  
  
  
  person * setName() {
         person * array;
         array = malloc (2 * sizeof(person));
  
         array-&gt;name = strdup("Robert");
         array++;
         array-&gt;name = strdup("Jose");
         return array;
  }
  
  
      int main()
      {
          person *array;
  
          array = setName();
  
          printf("First name is %s\n", array[0].name);
          printf("Second name is %s\n", array[1].name);
  
          return 0;
      }
  </code></pre>
  
  <p>In this example, array[0].name returns Jose, not Robert as I expected, and array[1].name is empty.</p>
  
  <p>However if I use </p>
  
  <pre><code>person * setName() {
         person * array;
         person * array_switch;
         array = malloc (2 * sizeof(person));
         array_switch = array;
         array_switch-&gt;name = strdup("Robert");
         array_switch++;
         array_switch-&gt;name = strdup("Jose");
         return array;
  }
  </code></pre>
  
  <p>It works as expected. array.name[0] returns Robert and array.name[1] returns Jose.</p>
  
  <p>Why does it require a second pointer for this example to work? Can I do it without using a second pointer AND still use pointer arithmetic? </p>
  
  <p>I already know this is another way to do it as well:</p>
  
  <pre><code>person * setName() {
         person * array;
         array = malloc (2 * sizeof(person));
         array[0].name = strdup("Robert");
         array[1].name = strdup("Jose");
         return array;
  }
  </code></pre>