/* Pointers Notes See detailed explanations in the html file Maria Hernandez */ #include // All examples are based on a 64-bit system typedef unsigned long UL; int main() { // 1 long array[] = {0xbeefdeabdeadbeef, 2, 3, 4}; int *pi = (int *)array; printf("pi[4]: %d\n", pi[4]); // output: pi[4]: 3 pi++; printf("%x\n", *pi); // output: beefdeab // 2 unsigned long array2[] = {4294967295, 250, 3, 4}; printf("array2[0]: 0x%0lx\n", array2[0]); // output: array2[0]: 0xffffffff int *pi2 = (int *)array2; pi2++; printf("%d\n", *pi2); // output: 0 // 3 long array3[] = {4294967296, 250, 3, 4}; int *pi3 = (int *)array3; printf("First 4 bytes are zero: 0x%04x\n", *pi3); // First 4 bytes are zero: 0x0000 // (These 4 zeroes do not represent 4 bytes, each byte is represented by 2 hexs. The 4 zeroes here // are because of the formatting). pi3++; printf("Followed by a 1: 0x%04x\n", *pi3); // output: Followed by a 1: 0x0001 // 4 long array4[] = {0xbeefdeabdeadbeef, 2, 3, 4}; char *pc = (char *)array4; pc = pc + 5; printf("0x%08x\n", *((int *)pc)); // output: 0x02beefde // 5 // Typecasting 1000 to a pointer to integer int *z = (int *)1000; // 1000 in hex is 0x3e8 z++; printf("%lu\n", (unsigned long)z); // output: 1004 printf("0x%016lx\n", (unsigned long)z); // output: 0x00000000000003ec // printf("seg fault %d\n", *z); // -> Try dereferencing it, it will seg fault // 6 // Typecasting 1000 to a pointer to pointer char **pointer_to_pointer = (char **)1000; pointer_to_pointer = pointer_to_pointer + 4; printf("%lu\n", (unsigned long)pointer_to_pointer); // output: 1032 // 7 short matrix[4][2] = {{0x1234,0x5678},{0x9012,0xabcd},{0xdf01,0xfedc},{0xba21,0x9876}}; // First part printf("base address of matrix: 0x%lx\n", (UL)matrix); // output: base address of matrix: 0x16f186f90 (for this one run - it's not always the same) printf("(UL)&(matrix[1][0]): 0x%lx\n", (UL)&(matrix[1][0])); // output: (UL)&(matrix[1][0]): 0x16f186f94 printf("(&(matrix[1][0]) + 4): 0x%lx\n", (unsigned long)(&(matrix[1][0])+4)); // output: (&(matrix[1][0]) + 4): 0x16f186f9c printf("*(&(matrix[1][0]) + 4): 0x%hx\n", *(&(matrix[1][0]) + 4)); // output: *(&(matrix[1][0]) + 4): 0xba21 // Second part unsigned char* cp = (unsigned char *)matrix; cp = cp + 7; printf("*cp 0x%hx\n", *cp); // output: *cp 0xab }