/* swapStructSolution.c Swaps 2 automatic struct values using pointers to the struct and the assignment operator "=" */ #include #include #include typedef struct { char *name; int year; /* 1=frosh, 2=soph etc */ } Person; /* Person is now a data type */ /* Note that we treat the structs as primatives as use direct assignment to copy the values stored in the structs. The assignment operator is to be used to assign the value of the entire struct at large. It is the programmer's responsibility to understand that pointer fields are copied by value thus the assignment is shallow copy of the dynamic structure that is pointed to */ void swapStructs( Person * ptr1, Person * ptr2 ) { Person temp; temp = *ptr1; *ptr1 = *ptr2; *ptr2 = temp; } int main( int argc, char *argv[]) { Person p1, p2; p1.name = malloc( strlen("Herman Munster")+1 ); /* malloc the name string */ strcpy( p1.name,"Herman Munster" ); p1.year = 4; p2.name = malloc( strlen("Gomez Addams")+1 ); /* malloc the name string */ strcpy( p2.name,"Gomez Addams" ); p2.year = 6; printf("Before structSwap:\n"); printf("P1: name %s, year %d\n", p1.name, p1.year ); printf("P2: name %s, year %d\n", p2.name, p2.year ); swapStructs( &p1, &p2 ); printf("After structSwap:\n"); printf("P1: name %s, year %d\n", p1.name, p1.year ); printf("P2: name %s, year %d\n", p2.name, p2.year ); free( p1.name ); /* no garbage */ free( p2.name ); /* no garbage */ return 0; } /* EOF */