结构体和指针,C语言的灵魂。面向对象我就不班门弄斧解释了。
首先,一个结构体:
struct Person
{
char* name;
int age;
int height;
int weight;
}
那么“造人”吧:
struct Person* Create_person(const char* name,int age,int height,int weight)
{
struct Person* who = malloc(sizeof(struct Person));
who->name=name;
who->age=age;
who->height=height;
who->weight=weight;
return who;
}
怎么“杀人”呢?
void Destroy_person(struct Person* who)
{
free(who->name); // be carefull
free(who);
}
输出“人”的信息:
void Print_person(struct person* who)
{
printf("Name:%s",who->name);
printf("Age:%d",who->age);
printf("height:%d",who->height);
printf("weight:%d",who->weight);
}
最后测试一下:
int main(int argc, char *argv[])
{
// make two people structures
struct Person *joe = Person_create(
"Joe Alex", 32, 64, 140);
struct Person *frank = Person_create(
"Frank Blank", 20, 72, 180);
// print them out and where they are in memory
printf("Joe is at memory location %p:\n", joe);
Person_print(joe);
printf("Frank is at memory location %p:\n", frank);
Person_print(frank);
// make everyone age 20 years and print them again
joe->age += 20;
joe->height -= 2;
joe->weight += 40;
Person_print(joe);
frank->age += 20;
frank->weight += 20;
Person_print(frank);
// destroy them both so we clean up
Person_destroy(joe);
Person_destroy(frank);
return 0;
}