/* ** Program name: pointers.c ** Purpose: to make pointers in C easy to understand. ** ** This program was created by ** Scott Wenger ** Box 802 ** Stevens Point, WI 54481 ** USA ** panther@wctc.net ** ** To understand pointers, compile and execute this program */ #include #include #include // for getch() char *messages[] = { "\nUnderstanding pointers in C\n", "x[1] is shorthand for *(x + 1)\n", "After memorizing that fact, pointers are easy!", "Wherever array notation is used, pointer notation", "can be substituted. Two examples appear below:\n" }; // First, let's declare z as an array of pointers to int int z[] = {640, 76, 123, 585, 39}; // Next, let's declare x as an array of pointers to char char *x[] = {"Aloha", "Goodbye", "Howdy", "Hello world!", "Hi"}; main() { int i; int *q; // declare q as pointer to int char **ptr; // declare ptr as pointer to pointer to char q = z; // point q to start of array z (same as q = &z[0]) ptr = x; // point ptr to start of array x (same as ptr = &x[0]) for (i = 0; i < 80; i++) printf("\n"); // portable clear screen for (i = 0; i < 50; i++) printf("-"); // display some dashes for (i = 0; i < 5; i++) printf("%s\n", *(messages + i) ); printf("// First, let's declare z as an array of pointers to int"); printf("\nint z[] = {640, 76, 123, 585, 39}; "); printf("\n// Next, let's declare x as an array of pointers to char"); printf("\nchar *x[] = {\"Aloha\", \"Goodbye\", \"Howdy\", \"Hello world!\", \"Hi\"};\n"); printf("\nchar **ptr; // declare ptr as pointer to pointer to char"); printf("\nint *q; // declare q as pointer to int "); printf("\nq = z; // point q to start of array z (same as q = &z[0])"); printf("\nptr = x; // point ptr to start of array x \n"); printf("\nExample 1: *(q + 2) is %d\n", *(q + 2) ); printf("\nExample 2: *(ptr + 3) points to \"%s\"", *(ptr + 3) ); printf("\n\nPress any key to to exit [ ]\b\b"); fflush(stdout); getch(); exit(0); }