Facebook
From Red Pelican, 6 Years ago, written in Plain Text.
This paste is a reply to Untitled from Chunky Giraffe - go back
Embed
Viewing differences between Untitled and Re: Untitled
#include 
#include 
#include 
#include 
struct Person {
 char *name;
 int age;
 int height;
 int weight;
};
struct Person *Person_create(char *name, int age, int height, int weight)
{
 struct Person *who = malloc(sizeof(struct Person));
 assert(who != NULL);
 who->name = strdup(name);
 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[])
{
 // create make two arrays we care about
 int ages[] 
people structures
 struct Person *joe 
{23, 43, 12, 89, 2};
 char *names[] 
Person_create(
 "Joe Alex", 32, 64, 140);
 struct Person *frank 
{
 "Alan", "Frank",
 "Mary", "John", "Lisa"
 };
 
Person_create(
 struct Person *frank = Person_create(
 "Frank Blank", 20, 72, 180);
 
// safely get the size of ages
 int count = sizeof(ages) / sizeof(int);
 int i = 0;
 
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);
 
// first way using indexing
 for(i = 0; i < count; i++) {
 printf("%s has %d 
make everyone age 20 years alive.\n",
 names[i], ages[i]);
 }
 printf("---\n");
 
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);
 
// setup the pointers to the start of the arrays
 int *cur_age = ages;
 char **cur_name = names;
 // second way using pointers
 for(i = 0; i < count; i++) {
 printf("%s is %d years old.\n",
 *(cur_name+i), *(cur_age+i));
 }
 printf("---\n");
 // third way, pointers are just arrays
 for(i = 0; i < count; i++) {
 printf("%s is %d years old again.\n",
 cur_name[i], cur_age[i]);
 }
 printf("---\n");
 // fourth way with pointers in a stupid complex way
 for(cur_name = names, cur_age = ages;
 for(cur_name = names, cur_age = ages;
 (cur_age - ages) < count;
 cur_name++, cur_age++)
 {
 printf("%s lived %d years 
destroy them both so far.\n",
 *cur_name, *cur_age);
 }
we clean up
 Person_destroy(joe);
 Person_destroy(frank);
 return 0;
}