Supposed I have structures like this
typedef struct _student {
int studentID;
char name[30];
char class[10];
char department[10];
} Student;
and the following function creates new variables of type Student:
Student *new_student(int id, char *name, char *class, char *dept) {
Student *s = (Student *)malloc(sizeof(Student *));
s->studentID = id;
strncpy(s->name, name, sizeof(s->name) - 1);
s->name[sizeof(s->name) - 1] = '\0';
strncpy(s->class, class, sizeof(s->class) - 1);
s->class[sizeof(s->class) - 1] = '\0';
strncpy(s->department, dept, sizeof(s->department) - 1);
s->department[sizeof(s->department) - 1] = '\0';
return s;
}
void display_student(Student *s) {
printf("Student: %d | %s | %s | %s\n", s->studentID, s->name, s->class, s->department);
}
To test my code, I just write something simple in my main()
int main() {
Student *s1 = new_student(20111201, "Lurther King Anders Something", "ICT-56", "SoICT");
Student *s2 = new_student(20111202, "Harry Potter", "ICT-56", "SoICT");
Student *s3 = new_student(20111203, "Hermione Granger", "ICT-56", "SoICT");
Student *s4 = new_student(20111204, "Ron Weasley", "ICT-56", "SoICT");
display_student(s1);
display_student(s2);
display_student(s3);
display_student(s4);
return 0;
}
However, the results is unexpected and weird to me:
Can someone please explain for me why the weird result is! I think I did things in a correct manner, I've applied safe use of strncpy, but I dont' understand the output.