1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| #include "csapp.h" #include <stdio.h>
void print_int(int x) { printf("int: %d\n", x); } void print_dbl(double x) { printf("double: %g\n", x); } void print_int_arr(int a[]) { int i; printf("int array: ["); for (i=0;i<=(sizeof(a))/sizeof(a[0]); i++) { printf("%d, ", a[i]); } printf("]\n"); } void print_default() { puts("unknown argument"); } #define print(X) _Generic((X), \ int: print_int, \ double: print_dbl, \ int*: print_int_arr, \ default: print_default)(X)
#define problem(x) printf("\n * Problem %s: \n", x) #define comment(x) printf("%s\n", x)
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, int len) { int i; for (i=0; i<len; i++) { printf(" %.2x", start[i]); } printf("\n"); }
void show_int(int x) { show_bytes((byte_pointer) &x, sizeof(int)); }
void show_float(float x) { show_bytes((byte_pointer) &x, sizeof(float)); }
void show_pointer(void* x) { show_bytes((byte_pointer) &x, sizeof(void *)); }
void swap(int *x, int *y) { *y = *x^*y; *x = *x^*y; *y = *x^*y; }
void reverse_array(int a[], int cnt) { int first, last; for (first=0, last=cnt-1; first < last; first++, last--) { swap(&a[first], &a[last]); }; }
int main() { int x = 1; float y = 1.0; show_int(x); show_float(y); show_pointer(&x); printf("Sizeof float is %lu \n", sizeof(float)); printf("Sizeof int is %lu \n", sizeof(int)); problem("2.6"); int a = 3510593; int b = 3510593.0; show_int(b); show_int(a); show_float(b); const char *s = "abcdef"; show_bytes((byte_pointer)s, strlen(s));
problem("2.10"); int aa = 1; int bb = 2; swap(&aa, &bb); print(aa); print(bb);
problem("2.11"); comment("Note that a ^ a = 0"); int a2[] = {1, 2, 3}; print(a2); reverse_array(a2, 3); print(a2);
problem("2.12"); int x12 = 0x87654321; printf("%x\n", x12 & 0xFF); printf("%x\n", ~( x12 ^ 0xFF )); printf("%x\n", x12 | 0xFF); printf("%x\n", ~( 0x11 ^ 0xFF )); }
|