diff --git a/c_pointer_sample_for_students.c b/c_pointer_sample_for_students.c new file mode 100644 index 0000000..21f712b --- /dev/null +++ b/c_pointer_sample_for_students.c @@ -0,0 +1,119 @@ +#include +#include + +#define MAX_STUDENTS_NUM 100 + +typedef struct { + char name[21]; + int age; + char addr[101]; +} student_t; + +typedef struct { + student_t stu[MAX_STUDENTS_NUM]; + int index; +} studentList_t; + +int initList_example(studentList_t **students) +{ + studentList_t *newList = (studentList_t *)malloc(sizeof (studentList_t)); + if (newList == NULL) { + return -1; + } + + memset(newList, 0, sizeof (studentList_t)); + *students = newList; + return 0; +} + +void initList_proc_example() +{ + studentList_t *students; + if (initList_example(&students)) { + printf("init error!\n"); + return; + } + printf("init ok.\n"); +} + +void initList_suggestion1(studentList_t *students) +{ + students->index = 0; + memset(students->stu, 0, sizeof (student_t) * MAX_STUDENTS_NUM); +} + +void initList_proc_suggestion1() +{ + studentList_t students; + initList_suggestion1(&students); +} + +studentList_t *initList_suggestion2() +{ + studentList_t *newList = (studentList_t *)malloc(sizeof (studentList_t)); + if (newList == NULL) { + return NULL; + } + + memset(newList, 0, sizeof (studentList_t)); + return newList; +} + +void initList_proc_suggestion2() +{ + studentList_t *students = initList_suggestion2(); + if (students == NULL) { + printf("init error!\n"); + return; + } + printf("init ok.\n"); +} + +typedef struct _studentLink_t { + struct _studentLink_t *next; + student_t info; +} studentLink_t; + +int initLink_example(studentLink_t **node) +{ + studentLink_t *newNode = (studentLink_t *)malloc(sizeof (studentLink_t)); + if (newNode == NULL) { + return -1; + } + + newNode->next = NULL; + *node = newNode; + return 0; +} + +void initLink_proc_example() +{ + studentLink_t *link; + if (initLink_example(&link)) { + printf("init error!\n"); + return; + } + + printf("init ok.\n"); +} + +studentLink_t *initLink_suggestion() +{ + studentLink_t *newNode = (studentLink_t *)malloc(sizeof (studentLink_t)); + if (newNode == NULL) { + return NULL; + } + + newNode->next = NULL; + return newNode; +} + +void initLink_proc_suggestion() +{ + studentLink_t *studentsLink = initLink_suggestion(); + if (studentsLink == NULL) { + printf("init error!\n"); + return; + } + printf("init ok.\n"); +}