title: Pass struct array to function with malloc
body: <p>I'am writing a program where I need to add students to a array of structs.</p>
  
  <p>Well, at the beginning I have the following struct array:</p>
  
  <pre><code>struct student *students[4];
  </code></pre>
  
  <p>After the declaration I add students like this to the array (just to have examples ...):</p>
  
  <pre><code>  students[0] = malloc(sizeof(struct student));
    students[0]-&gt;firstname = "Max";
    students[0]-&gt;secondname = "Taler";
    students[0]-&gt;number = 123456l;
  </code></pre>
  
  <p>...</p>
  
  <p>Now I have to write a additional function, where I can pass the array as a parameter and add a new student.</p>
  
  <p>So my function looks like this:</p>
  
  <pre><code>void add_student(struct student *students[],char *fristname, char *secondname, long number)
  {
      int i=0;
      int new_position=0;
      int return_value = 0;
      // Search for the first available position for a new student 
      for(i=0; i&lt;sizeof(students); i++)
      {
          if(students[i]==NULL)
          {
              new_position=i;
              return_value = 1;
              break;
          }
      }
  
      struct student *new_student = malloc(sizeof(struct student));
      students[new_position] = new_student;
  
      students[new_position]-&gt;fristname = fristname;
      students[new_position]-&gt;secondname = secondname;
      students[new_position]-&gt;number = number;
  
     return return_value; 
  }
  </code></pre>
  
  <p>I call the function with this code:</p>
  
  <pre><code>add_student(students, "Anni", "Karls", 123232);
  </code></pre>
  
  <p>But now my <strong>issue</strong>: In my "add_student" function I get an array that has a strange structur: it includes itself as the first element and every other element is shifted by 1 element. </p>
  
  <p>Cant figure out what the problem is ... Can somebody please help? </p>
  
  <p>EDIT: Somebody asked me, how this can be. How the array can include "itself" as the first element.</p>
  
  <p>Well, here are screenshots of the debugger (xCode):</p>
  
  <p>Before entering "add_student":</p>
  
  <p><a href="https://i.stack.imgur.com/ZAMTF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZAMTF.png" alt="before entering &quot;add_student&quot;"></a></p>
  
  <p>After entering "add_student" -> IN the function "add_student":</p>
  
  <p><a href="https://i.stack.imgur.com/NLF5y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NLF5y.png" alt="after entering &quot;add_student&quot; -&gt; IN the function &quot;add_student&quot;"></a> </p>
  
  <p>As you see, "students" has now 5 elements ... </p>