/* * ISA 563, Spring 2011 * Copyleft by Muhammad Abdulla */ #include /* * varptr.c -- demonstrates variable and pointer properties */ int main (int argc, char *argv[] ) { int score = 100; int *score_ptr; int total_score = 2345; int *total_score_ptr; score_ptr = &score; total_score_ptr = &total_score; struct node { double value; struct node *next; }; struct node head; head.value = 12.34; struct node *node_ptr = &head; // properties of a variable fprintf(stdout, "value of score = %d\n", score); fprintf(stdout, "address of score = %p\n", &score); fprintf(stdout, "size of score = %d\n", sizeof(score)); fprintf(stdout, "address of total_score = %p\n", &total_score); printf("\n"); // properties of a pointer fprintf(stdout, "value of score_ptr = %p\n", score_ptr); fprintf(stdout, "value pointed by score_ptr= %d\n", *score_ptr); fprintf(stdout, "address of score_ptr= %p\n", &score_ptr); fprintf(stdout, "sizeof of score_ptr= %d\n", sizeof(score_ptr)); fprintf(stdout, "sizeof of *score_ptr= %d\n", sizeof(*score_ptr)); fprintf(stdout, "sizeof of *node_ptr= %d\n", sizeof(*node_ptr)); // we can update the value of a variable through a pointer pointing to it *score_ptr = 200; fprintf(stdout, "\nafter '*score_ptr = 200;':\n"); fprintf(stdout, "value of score = %d\n", score); fprintf(stdout, "address of score = %p\n", &score); // we can update the value (address held by the pointer) too. score_ptr = total_score_ptr; fprintf(stdout, "\nafter 'score_ptr = total_score_ptr;':\n"); fprintf(stdout, "value of score = %d\n", score); fprintf(stdout, "address of score = %p\n", &score); fprintf(stdout, "value of score_ptr = %p\n", score_ptr); fprintf(stdout, "address of score_ptr = %p\n", &score_ptr); fprintf(stdout, "value pointed by score_ptr = %d\n", *score_ptr); // pointer access to struct fields fprintf(stdout, "\nhead.value = %g\n", head.value); fprintf(stdout, "node_ptr->value = %g\n", node_ptr->value); return 0; }