/* Keeping track of your friends using structs Ferworn F06 */ #include <string.h> #include <stdio.h> #include <stdlib.h> struct friend { char name[60]; int age; int likeability; }; int howmanyfriends() { int howmany; printf("How many friends will you have?\n"); scanf("%d",&howmany); return howmany; } struct friend *makefriendspace(int howmany) { return (struct friend *) malloc(sizeof(struct friend) * howmany); } struct friend addfriend() { struct friend temp; printf("Enter the friend's name: "); scanf("%s",temp.name); printf("Enter their age: "); scanf("%d",&temp.age); printf("How much do you like them? "); scanf("%d",&temp.likeability); printf("\n"); return temp; } void printfriends_array(struct friend myfriends[], int number) { int i; for(i=0;i<=number;i++) { printf("Friend #: %d\n",i); printf("Name: %s\n",myfriends[i].name); printf("Age: %d\n",myfriends[i].age); printf("Likeability: %d\n",myfriends[i].likeability); printf("===============\n\n"); } } void printfriends_pointer(struct friend *myfriends, int number) { int i; for(i=0;i<=number;i++) { printf("Friend #: %d\n",i); printf("Name: %s\n",(myfriends+i)->name); printf("Age: %d\n",(myfriends+i)->age); printf("Likeability: %d\n",(myfriends+i)->likeability); printf("===============\n\n"); } } int main() { struct friend *myfriends; int howmany,sofar = 0; howmany = howmanyfriends(); myfriends = makefriendspace(howmany); myfriends[sofar++] = addfriend(); myfriends[sofar] = addfriend(); printfriends_array(myfriends, sofar); printfriends_pointer(myfriends, sofar); /* let's print our your first friend manually using pointer notation */ free(myfriends); }