version of ex16 with structs created on the stack, using dot syntax instead of ->, passing by value
This commit is contained in:
parent
55fddaff46
commit
9d258d22b8
56
ex16.c
56
ex16.c
@ -10,64 +10,36 @@ struct Person {
|
|||||||
int weight;
|
int weight;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct Person *Person_create(char *name, int age, int height, int weight)
|
void Person_print(struct Person who)
|
||||||
{
|
{
|
||||||
struct Person *who = malloc(sizeof(struct Person));
|
printf("Name: %s\n", who.name);
|
||||||
assert(who != NULL);
|
printf("\tAge: %d\n", who.age);
|
||||||
|
printf("\tHeight: %d\n", who.height);
|
||||||
who->name = strdup(name);
|
printf("\tWeight: %d\n", who.weight);
|
||||||
who->age = age;
|
|
||||||
who->height = height;
|
|
||||||
who->weight = weight;
|
|
||||||
|
|
||||||
return who;
|
|
||||||
}
|
|
||||||
|
|
||||||
void Person_destroy(struct Person *who)
|
|
||||||
{
|
|
||||||
assert(who != NULL);
|
|
||||||
|
|
||||||
free(who->name);
|
|
||||||
free(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[])
|
int main(int argc, char *argv[])
|
||||||
{
|
{
|
||||||
// make two people structures
|
// make two people structures
|
||||||
struct Person *joe = Person_create(
|
struct Person joe = {"Joe Alex", 32, 64, 140};
|
||||||
"Joe Alex", 32, 64, 140);
|
struct Person frank = {"Frank Blank", 20, 72, 180};
|
||||||
|
|
||||||
struct Person *frank = Person_create(
|
|
||||||
"Frank Blank", 20, 72, 180);
|
|
||||||
|
|
||||||
// print them out and where they are in memory
|
// print them out and where they are in memory
|
||||||
printf("Joe is at memory location %p:\n", joe);
|
printf("Joe is at memory location %p:\n", &joe);
|
||||||
Person_print(joe);
|
Person_print(joe);
|
||||||
|
|
||||||
printf("Frank is at memory location %p:\n", frank);
|
printf("Frank is at memory location %p:\n", &frank);
|
||||||
Person_print(frank);
|
Person_print(frank);
|
||||||
|
|
||||||
// make everyone age 20 years and print them again
|
// make everyone age 20 years and print them again
|
||||||
joe->age += 20;
|
joe.age += 20;
|
||||||
joe->height -= 2;
|
joe.height -= 2;
|
||||||
joe->weight += 40;
|
joe.weight += 40;
|
||||||
Person_print(joe);
|
Person_print(joe);
|
||||||
|
|
||||||
frank->age += 20;
|
frank.age += 20;
|
||||||
frank->weight += 20;
|
frank.weight += 20;
|
||||||
Person_print(frank);
|
Person_print(frank);
|
||||||
|
|
||||||
// destroy them both so we clean up
|
|
||||||
Person_destroy(joe);
|
|
||||||
Person_destroy(frank);
|
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user