完成习题16
This commit is contained in:
parent
e4d4133009
commit
d6bbef323b
BIN
ex16/.ex16.c.swp
BIN
ex16/.ex16.c.swp
Binary file not shown.
|
@ -43,7 +43,7 @@ struct Person *Person_create(char *name, int age, int height, int weight)
|
|||
void Person_destroy(struct Person *who)
|
||||
{
|
||||
// 判断结构体是否为空
|
||||
assert(who != NULL);
|
||||
// assert(who != NULL);
|
||||
|
||||
// 先释放name所占用的空间,再销毁结构体
|
||||
free(who -> name);
|
||||
|
@ -84,11 +84,14 @@ int main(int argc, char *argv[])
|
|||
|
||||
frank -> age += 20;
|
||||
frank -> weight += 20;
|
||||
Person_destroy(frank);
|
||||
Person_print(frank);
|
||||
// Person_print(NULL);
|
||||
|
||||
// destroy them both so we clean up
|
||||
Person_destroy(joe);
|
||||
Person_destroy(frank);
|
||||
// Person_destroy(NULL);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
Binary file not shown.
|
@ -0,0 +1,70 @@
|
|||
#include <stdio.h>
|
||||
#include <assert.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
struct Person
|
||||
{
|
||||
char name[20];
|
||||
int age;
|
||||
int height;
|
||||
int weight;
|
||||
};
|
||||
|
||||
struct Person Person_create(char name[], int name_length, int age, int height, int weight)
|
||||
{
|
||||
struct Person who;
|
||||
|
||||
for (int i = 0; i < name_length; ++i)
|
||||
{
|
||||
who.name[i] = name[i];
|
||||
}
|
||||
|
||||
who.name[name_length - 1] = '\0';
|
||||
who.age = age;
|
||||
who.height = height;
|
||||
who.weight = weight;
|
||||
|
||||
return who;
|
||||
}
|
||||
|
||||
void Person_print(struct Person who)
|
||||
{
|
||||
printf("Name: %s\n", who.name);
|
||||
printf("\tAge: %d\n", who.age);
|
||||
printf("\tHeight: %d\n", who.height);
|
||||
printf("\tWeight: %d\n", who.weight);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
char name1[20] = "Joe Alex\0";
|
||||
char name2[20] = "Frank Blank\0";
|
||||
// make two people structures
|
||||
struct Person joe = Person_create(name1, 20, 32, 64, 140);
|
||||
|
||||
struct Person frank = Person_create(name2, 20, 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;
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
http://ewm.ptpress.com.cn:8085/preview?qrCode=qr2018001491
|
Loading…
Reference in New Issue