直接上代码,这个项目通俗易懂。
#include <stdio.h>
#include <string.h>
#define NAME_LEN 40
#include <assert.h>
typedef struct {
char name[NAME_LEN];
unsigned int id;
float shoe_size;
}Student;
Student new_student(const char name[], unsigned int id, float shoe_size){
/*create student struct variable*/
Student student;
/*storing infor into structure*/
if(name == NULL)
strcpy(student.name, "");
if(name != NULL && strlen(name) > 39)
{
strncpy(student.name, name, 39);
student.name[39]= '\0';
}
if(name != NULL && strlen(name) < 39)
strcpy(student.name, name);
student.id= id;
student.shoe_size= shoe_size;
/*return a new stucture */
return student;
}
void init_student(Student *const student, const char name[], unsigned int id,
float shoe_size){
if(student == NULL)
return;
if(name == NULL)
strcpy(student -> name, "");
else
strcpy(student -> name, name);
student -> id= id;
student -> shoe_size= shoe_size;
}
unsigned int has_id(Student student, unsigned int id){
if(student.id != id)
return 0;
return 1;
}
unsigned int has_name(Student student, const char name[]){
int a= 0;
if(name == NULL)
return 0;
a= strcmp(student.name, name);
if(a != 0)
return 0;
return 1;
}
unsigned int get_id(Student student){
return student.id;
}
float get_shoe_size(Student student){
return student.shoe_size;
}
Student change_shoe_size(Student student, float new_shoe_size){
student.shoe_size= new_shoe_size;
return student;
}
void change_name(Student *const student, const char new_name[]){
if(student == NULL)
return;
if(new_name == NULL){
strcpy(student -> name, "");
return;
}
if(strlen(new_name) > 39)
{
strncpy(student -> name, new_name, 39);
strcat(student -> name, "\0");
}
strcpy(student -> name, new_name);
}
/*
int main(void) {
Student s= new_student("Hao", 11111, 8.0);
should return 0, and by the way not crash */
/*
assert(!has_name(s, NULL));
assert(has_name(s, "Hao"));
/* should set the student's name to an empty string, and not crash */
/*change_name(&s, NULL);
assert(has_name(s, ""));
printf("Yes!\n");
return 0;
}
*/
int main(void) {
Student s= new_student("Penelope", 38463, 5.0);
change_name(&s, "Penny");
assert(has_id(s, 38463));
assert(get_id(s) == 38463);
assert(has_name(s, "Penny"));
assert(get_shoe_size(s) == 5.0);
printf("Yes!\n");
return 0;
}