// The main function that will be run when the file is run from bash int main(int argc, char *argv[]) { // make two Person structures and then create pointers to them struct Person *joe = person_create( "Joe Alex", 32, 64, 140); struct Person *frank = person_create( "Frank Black", 20, 72, 180); // Print out where each is in memory (possible because they are lvalues) printf("Joe is at memory location %p:\n", joe); person_print(joe); printf("Frank is at memory location %p:\n", frank); person_print(frank); // We can do assignment to the variables we assigned for our Person struct joe->age += 20; joe->height -= 2; joe->weight += 40; person_print(joe); frank->age += 20; frank->weight += 20; person_print(frank); // Clean the structs out of memory before the program ends person_destroy(joe); // valgrind shows leaked bytes if not called person_destroy(frank); // person_destroy(NULL); // passing NULL causes SIGABRT error return 0; }
/* this program illustrates how to use void* as a generic pointer, how to use pointer casts to get the generic pointer interpreted according to what type of value it points to, and the danger of making an incorrect cast */ int main (int argc, char ** argv) { struct tm now; /* standard struct for storing a time value */ double lightspeed; Person * albert; /* pointer to our custom struct person */ void * generic_pointer; /* let's read the clock, it gets stored in a standard struct tm (from the time.h header) */ if (0 != clock_read (&now)) { printf ("failed to read the clock\n"); return 1; } /* the speed of light as a double-precision floating point number */ lightspeed = 299792458.0; /* Albert Einstein was born on March 14, 1879. His age depends on today's date... */ albert = person_create ("Albert Einstein", (now.tm_mon >= 3 && now.tm_mday >= 14) ? now.tm_year + 1901 - 1879 : now.tm_year + 1900 - 1879); /* ************************************************** * NOW FOR THE FUN PART ***************************** * **************************************************/ /* the generic pointer can store the address of any of our variables */ generic_pointer = &now; printf ("the date and time is\n"); clock_print (&now); generic_pointer = &lightspeed; printf ("the speed of light is\n %g m/s\n", *(double*)generic_pointer); generic_pointer = albert; printf ("the person is\n"); person_print (generic_pointer); return 0; }