title: Making a deep copy of a struct...making a shallow copy of a struct
body: <p>There are questions LIKE this one, but they are not similar enough to my specific question FOR ME to pick up on.</p>
  
  <p>My question is about how to make a deep copy of a struct with pointers as members and how to make a SHALLOW copy of a struct with  pointers as members. And then, just for reference, how to make a a deep copy of a struct WITHOUT pointer members and how to make a shallow copy of a struct WITHOUT pointer members (not sure if that last one makes sense).</p>
  
  <p>Let's say we have this:</p>
  
  <pre><code>typedef struct Student
  {
      char* first_name; 
      char* last_name; 
      int grade;
      long id;
  } Student;
  </code></pre>
  
  <p>Here is a generic function I made to create a student (the header is being difficult to format):</p>
  
  <pre><code>Student* create_student(const char* first_name, const char* last_name, int grade,long id)
  
  {
  
     Student *newStudentp = (malloc(sizeof(Student)));
  
     newStudentp -&gt; last_name = (malloc((strlen(last_name) + 1)  * sizeof(char)));
     newStudentp -&gt; first_name = (malloc((strlen(first_name) + 1)  * sizeof(char)));
  
     strncpy(newStudentp -&gt; first_name, first_name, strlen(first_name) + 1);
     strncpy(newStudentp -&gt; last_name, last_name, strlen(last_name) + 1);
  
     newStudentp -&gt; grade = grade;
     newStudentp -&gt; id = id;
  
  
     return newStudentp;
  }
  </code></pre>
  
  <p>My attempt to make a deep and a shallow copy;</p>
  
  <pre><code>int main()
  {
      Student *s1 = create_Student("Bo","Diddly", 100, 221);
      Student *s2 = create_Student("Leeroy","Jenkins",50,1337);
      memcpy(&amp;s2,&amp;s1,sizeof(Student)); //shallow copy of s1 INTO s2?
      return 0;
  }
  </code></pre>
  
  <p>For deep copies of structs with pointer members I know we must make OUR OWN copy function that does something sensible with pointers. What that sensible thing is...I'm not sure...so here is my attempt at this DEEP copy.</p>
  
  <pre><code>void copy_Student(Student *s1, Student *s2)
  {
     s2 -&gt; grade = s1 -&gt; grade;
     s2 -&gt; id = s1 -&gt; id;
     s2 -&gt; first_name = s1 -&gt; *first_name;
     s2 -&gt; last_name = s1 -&gt; *last_name;
  
  }
  </code></pre>
  
  <p>The other part of my question (structs WITHOUT pointers as members) can probably just be explained verbally.</p>
  
  <p>EDITED AFTER READING HELPFUL COMMENTS:</p>
  
  <p>Shallow copy:
          memcpy(s2,s1,sizeof(Student));</p>
  
  <p>Deep copy:</p>
  
  <pre><code>void free_student(Student* stu)
  {
      free(stu -&gt; first_name);
      free(stu -&gt; last_name);
  }
  
  void copy_Student(Student *s1, Student *s2)
  {
      s2 -&gt; grade = s1 -&gt; grade;
      s2 -&gt; id = s1 -&gt; id;
      s2 -&gt; first_name = strdup(s1 -&gt; first_name);
      s2 -&gt; last_name = strdup(s1 -&gt; last_name);
  }
  </code></pre>