There are questions LIKE this one, but they are not similar enough to my specific question FOR ME to pick up on.
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).
Let's say we have this:
typedef struct Student
{
char* first_name;
char* last_name;
int grade;
long id;
} Student;
Here is a generic function I made to create a student (the header is being difficult to format):
Student* create_student(const char* first_name, const char* last_name, int grade,long id)
{
Student *newStudentp = (malloc(sizeof(Student)));
newStudentp -> last_name = (malloc((strlen(last_name) + 1) * sizeof(char)));
newStudentp -> first_name = (malloc((strlen(first_name) + 1) * sizeof(char)));
strncpy(newStudentp -> first_name, first_name, strlen(first_name) + 1);
strncpy(newStudentp -> last_name, last_name, strlen(last_name) + 1);
newStudentp -> grade = grade;
newStudentp -> id = id;
return newStudentp;
}
My attempt to make a deep and a shallow copy;
int main()
{
Student *s1 = create_Student("Bo","Diddly", 100, 221);
Student *s2 = create_Student("Leeroy","Jenkins",50,1337);
memcpy(&s2,&s1,sizeof(Student)); //shallow copy of s1 INTO s2?
return 0;
}
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.
void copy_Student(Student *s1, Student *s2)
{
s2 -> grade = s1 -> grade;
s2 -> id = s1 -> id;
s2 -> first_name = s1 -> *first_name;
s2 -> last_name = s1 -> *last_name;
}
The other part of my question (structs WITHOUT pointers as members) can probably just be explained verbally.
EDITED AFTER READING HELPFUL COMMENTS:
Shallow copy: memcpy(s2,s1,sizeof(Student));
Deep copy:
void free_student(Student* stu)
{
free(stu -> first_name);
free(stu -> last_name);
}
void copy_Student(Student *s1, Student *s2)
{
s2 -> grade = s1 -> grade;
s2 -> id = s1 -> id;
s2 -> first_name = strdup(s1 -> first_name);
s2 -> last_name = strdup(s1 -> last_name);
}