1.屏蔽assert函数
#define NDEBUG ("no debug") //shield the function of assert ... #include <assert.h> #include <stdlib.h> void open_record(char *record_name) { assert(record_name!=NULL); /* Rest of code */ printf("\nRecord name is:%s\n", record_name); } int main(void) { open_record(NULL); open_record("I love janesnf..."); open_record(NULL); return 0; }
2. 调用atexit
#include <stdio.h> #include <stdlib.h> void test_atexit0(void) { printf("\nHosfore 000000 is using atexit function ...\n"); } void test_atexit(void) { printf("\nHosfore is using atexit function ...\n"); } int main() { int i = 0; atexit(test_atexit); atexit(test_atexit0); atexit(test_atexit); atexit(test_atexit0); for (; i < 100; i++) printf("\n----\n"); return 0; }
3.调用二分搜索函数,搜索从数组的平均值开始
#include <stdlib.h> #include <stdio.h> #include <assert.h> #define DEBUG 0 int compare(const void *key, const void *current) { assert(key != NULL); assert(current != NULL); #if(DEBUG) printf("\nIn %s and key val:%d, current val:%d\n",\ __func__, *(int*)key, *(int*)current); #endif if (*(int*)key > *(int*)current) return 1; else if (*(int*)key == *(int*)current) return 0; else return -1; } int main() { int key = 2, arr[10], i = 0, *rt; for (; i < 10; i++) arr[i] = 2+i; #if(DEBUG) printf("\nIn %s and sizeof arr is:%d, sizeof int is:%d\n",\ __func__, sizeof(arr)/sizeof(arr[0]), sizeof(int)); #endif rt = bsearch(&key, arr, sizeof(arr)/sizeof(arr[0]), sizeof(int), compare); if (rt) printf("\nbsearch result of key:%d is:%d and memory addr is:%p\n",\ key, *rt, rt); return 0; }
4.大小写字母转换函数调用
#include<ctype.h> #include<stdio.h> #include<string.h> int main(void) { int loop; char string[]="THIS IS A TEST"; printf("Orig: %s\n",string); for(loop=0;loop<strlen(string);loop++) string[loop]=tolower(string[loop]); printf("Tolowered: %s\n",string); return 0; }
5.求结构体属性在其内部地址偏移函数offsetof
#include<stddef.h> #include<stdio.h> int main(void) { struct user{ char name[50]; char alias[50]; int level; }; printf("level is the %d byte in the user structure.\n", offsetof(struct user,level)); }
6.支持不定参数个数的函数(源自网络)
#include<stdarg.h> #include<stdio.h> void sum(char *, int, ...); int main(void) { sum("The sum of 10+15+13 is %d.\n",3,10,15,13); return 0; } void sum(char *string, int num_args, ...) { int sum=0; va_list ap; int loop; va_start(ap,num_args); for(loop=0;loop<num_args;loop++) sum+=va_arg(ap,int); printf(string,sum); va_end(ap); }