/* ptr.c - pointer and array example * by R. Teather, COSC 2P13 Spring 2009 */ #include int main(void) { int i = 0; //declare and initialize our array int ary[10] = {5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; //declare an int, and a pointer to that int // note that &x refers to the address of x, iPtr stores this int x = 15; int* iPtr = &x; printf("Pointer example: \n\n"); //if we print out the value of iPtr (as hex) and the address of x, they are the same printf("iPtr = %x, &x = %x\n", iPtr, &x); //use the * operator to dereference the pointer and get the value it points to (i.e., value of x) printf("*iPtr = %d, x = %d\n\n\n", *iPtr, x); printf("Array example: \n\n"); //arrays are actually memory addresses too printf("ary = %x, &ary = %x\n", ary, &ary); //we can print out the contents of the array using subscript notation (as usual) // or by pointer arithmetic, i.e., adding the offset to the array's base memory address // to get to a specific element of the array in memory for( i = 0; i < 10; i++) { printf("ary[i] = %d, *(ary+i) = %d\n", ary[i], *(ary+i)); printf("&ary[i] = %x, (ary+i) = %x\n", &ary[i], (ary+i)); } return 0; }