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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
// atexit(ptr) 注册退出事件 #include <stdio.h> #include <stdlib.h> void event1(void); void event2(void); int main(int argc, char const *argv[]) { atexit(event1); atexit(event2); /* 当程序主动调用exit()或main函数中return触发exit()后 会后进先出地执行被注册到atexit()中的函数 this is the event2 this is the event1 */ return 0; } void event1(void) { puts("this is the event1"); } void event2(void) { puts("this is the event2"); } // 快速排序qsort(数组指针,数组长度,单个数组元素长度,自定义排序函数指针) #include <stdio.h> #include <stdlib.h> #define NUM 40 void fillarray(double ar[], int n); void showarray(const double ar[], int n); int mycomp(const void * p1, const void * p2); int main(int argc, char const *argv[]) { double vals[NUM]; fillarray(vals, NUM); puts("Random list:"); showarray(vals, NUM); qsort(vals, NUM, sizeof(double), mycomp); puts("\nSorted list:"); showarray(vals, NUM); return 0; } void fillarray(double ar[], int n) { int i; for (i = 0; i < n; ++i) { ar[i] = (double)rand() / ((double)rand() + 0.1); } } void showarray(const double ar[], int n) { int i; for (i = 0; i < n; ++i) { printf("%9.4f ", ar[i]); if (i % 6 == 5) { putchar('\n'); } } } int mycomp(const void * p1, const void * p2) { // 需要使用指向double的指针访问值 const double * a1 = (const double *)p1; const double * a2 = (const double *)p2; if (*a1 < *a2) { return -1; } else if (*a1 == *a2) { return 0; } else { return 1; } } // 诊断库(用于调试) #include <stdio.h> #define NDEBUG //如果调试完毕,直接在包含assert.h之前定义宏NDEBUG,就能禁用assert()功能 #include <assert.h> int main(int argc, char const *argv[]) { int i = 0; assert(i == 0); puts("ok"); // 断言当i=0时,程序直接退出,输出相关错误信息(文件名、行号) assert(i != 0); puts("done"); return 0; } // 可变参数 stdarg.h #include <stdio.h> #include <stdarg.h> double sum(int, ...); int main(int argc, char const *argv[]) { /* 在函数原型中使用省略号 在函数定义中创建一个va_list类型的变量 用宏将该变量初始化为一个参数列表 用宏访问这个参数列表 用宏完成清理工作 void f1(int n, ...); //合法 int f2(int n, const char * s, ...); //合法 char f3(char c1, ..., char c2); //不合法,省略号必须是最后一个参量 double f4(); //不合法,没有任何参量 */ double s, t; // 第一个参数3,描述了后面有3个可变参数 // printf()中估计是统计%d、%s等的数量,来计算出可变参数数量的 s = sum(3, 1.1, 2.5, 13.3); t = sum(6, 1.1, 2.1, 13.1, 4.1, 5.1, 6.1); printf("return value for sum(3, 1.1, 2.5, 13.3) %g\n", s); printf("return value for sum(6, 1.1, 2.1, 13.1, 4.1, 5.1, 6.1) %g\n", t); return 0; } double sum(int lim, ...) { va_list ap; //声明用于存放参数的变量 double tot = 0; int i; va_start(ap, lim); //把ap初始化为参数列表 for (i = 0; i < lim; ++i) { tot += va_arg(ap, double); //访问参数列表中的每一个选项 } va_end(ap); //清理工作 return tot; } |