test1()1 void test1() {
2 int a = 3;
3 int* pb = &a;
4 int c = *pb;
5 printf("Reading from a pointer: %d %d\n", a, c);
6 *pb = 4;
7 printf("Writing to a pointer: %d\n", a);
8 printf("Testing casts: %d %g %g %d\n", 3, (float) 3, 4.5, (int) 4.5);
9 }
10
test2()11 void test2() {
12 int x = 4;
13 int px = &x;
14 // int z = * px; // An error, expected a pointer type
15 int y = * (int*) px;
16 printf("Testing reading (int*): %d\n", y);
17 }
18
test3()19 void test3() {
20 int px = (int) malloc(120);
21 * (int*) px = 8;
22 * (int*) (px + 4) = 9;
23 printf("Testing writing (int*): %d %d\n", * (int*) px, * (int*) (px + 4));
24 free((void*) px);
25 }
26
test4()27 void test4() {
28 int x = 0x12345678;
29 int px = &x;
30 int a = * (char*) px;
31 int b = * (char*) (px + 1);
32 int c = * (char*) (px + 2);
33 int d = * (char*) (px + 3);
34 printf("Testing reading (char*): 0x%02x 0x%02x 0x%02x 0x%02x\n", a, b, c, d);
35 }
36
test5()37 void test5() {
38 int x = 0xFFFFFFFF;
39 int px = &x;
40 * (char*) px = 0x21;
41 * (char*) (px + 1) = 0x43;
42 * (char*) (px + 2) = 0x65;
43 * (char*) (px + 3) = 0x87;
44 printf("Testing writing (char*): 0x%08x\n", x);
45 }
46
f(int b)47 int f(int b) {
48 printf("f(%d)\n", b);
49 return 7 * b;
50 }
51
test6()52 void test6() {
53 int fp = &f;
54 int x = (*(int(*)()) fp)(10);
55 printf("Function pointer result: %d\n", x);
56 }
57
test7()58 void test7() {
59 int px = (int) malloc(120);
60 * (float*) px = 8.8f;
61 * (float*) (px + 4) = 9.9f;
62 printf("Testing read/write (float*): %g %g\n", * (float*) px, * (float*) (px + 4));
63 free((void*) px);
64 }
65
test8()66 void test8() {
67 int px = (int) malloc(120);
68 * (double*) px = 8.8;
69 * (double*) (px + 8) = 9.9;
70 printf("Testing read/write (double*): %g %g\n", * (double*) px, * (double*) (px + 8));
71 free((void*) px);
72 }
73
74
main()75 int main() {
76 test1();
77 test2();
78 test3();
79 test4();
80 test5();
81 test6();
82 test7();
83 test8();
84 return 0;
85 }
86