title: Allocate memory for a pointer to a struct inside a function
body: <p>I am trying to write a separate program that calls a function to dynamically allocate memory for a certain number of "student" structs.</p>
  
  <p>My main program was too large to mess with so I created a smaller program to help me more easily figure out what I'm doing:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include "memtest.h"
  
  void structMemInit(myName **);
  
  int main(void){
  
      myName *myNameIs;
  
      structMemInit(&amp;myNameIs);
  
      printf("%s\n", myNameIs[1].name);
  
      return 0;
  }
  
  void structMemInit(myName **myNameIs){
      *myNameIs = (myName *) calloc(5, sizeof(myName));
      if(myNameIs == NULL){
          printf("allocating memory didn't work!\n");
          exit(1);
      }
      else if(myNameIs != NULL)
          (*myNameIs)[1].name = "Zach";
  }
  </code></pre>
  
  <p>the memtest.h file is:</p>
  
  <pre><code>typedef struct{
      char *name;
  }myName;
  </code></pre>
  
  <p>All the above program is trying to do is pass a pointer to a struct into the function "structMemInit" and allocate clean space for the struct. Then to see show that it worked, I am setting the variable char to a name. After all this happens, you leave the function and go back to main. Then I print the name in the struct to show it worked.</p>
  
  <p>When run, the program always gives a segfault. </p>
  
  <p>In case you are wondering why I have a separate .h file, my actual program is much larger and has several globally declared structs and I am required by my instructor to keep a separate .h for those structs.</p>
  
  <p>Thanks!
  Zach</p>