title: How to access struct members using pointers
body: <p>I created a structure in a header file to store student information. I initialize these member variable in a function called createStudent(). The createStudent() function returns a pointer to a newly initialized student. Now, when I test that this all works I get some unexpected results. </p>
  
  <p>The code compiles and runs, however, only the first access of the students information returns useful values. In the code below I print out the students age first and I get the correct age, but the gpa and num values are garbage values. However, if I comment out the print statement for the students age, the gpa value is correct and the num value is still garbage. It seems that only the first access returns goof values. Now I'm fairly certain this is an issue to do with my pointers and memory allocation, I just don't know what the problem is.</p>
  
  <p>I initially thought that memory was being freed up after the first access (I don't know why this would happen but that what seemed to be happening). So I tried to use malloc in order to make sure there was memory available at all times storing the students info, but the results did not change.</p>
  
  <p>I have also tried re-assigning age in the createStudent() function after gpa and num were assigned, but age still gets the corrected value and gpa and num have garbage values.</p>
  
  <p>If you guys need any more information concerning this please let me know.</p>
  
  <h1>Header File:</h1>
  
  <pre><code>    typedef struct Students{
  
           int num;                //holds the students number
           char name[256];         //holds the students name
           int age;                //holds the students age
           int gpa;                //holds the students grade point  average
  
      }Student;
  
      Student * createStudent();
  </code></pre>
  
  <h1>Implementation file:</h1>
  
  <pre><code>    Student * createStudent(){
           Student newStud;
           Student *studPtr;
  
           newStud.age = 10;       
           newStud.gpa = 5;        
           newStud.num = 307234;   
  
           studPtr = &amp;newStud;
  
           return studPtr;
      }
  </code></pre>
  
  <h1>Main File:</h1>
  
  <pre><code>    int main(int argc, char *argv[]){
           int retCode = 0;
  
           Student *stdPtr = createStudent();
  
           printf("The students age is: %d\n", stdPtr-&gt;age);
           printf("The students gpa is: %d\n", stdPtr-&gt;gpa);
           printf("The students number is: %d\n", stdPtr-&gt;num);
  
           return retCode;
      }
  </code></pre>