一个在线的C库查询的地址:http://www.cplusplus.com/reference/clibrary/
可变函数参数的用法
#include <stdio.h>
#include <stdarg.h>
double arv(int n, ...)
{
double sum=0;
va_list arg;
va_start(arg,n);
for (int i=0;i<n;i++)
sum+=va_arg(arg,int);
va_end(arg);
return sum/n;
}
int main()
{
printf("%lf\n",arv(3,1,2,3));
printf("%lf\n",arv(2,1,2));
getchar();
return 0;
}
malloc, calloc, realloc的区别
#include <stdlib.h>
int main()
{
int num=5;
int *p;
// allocate memory
p=(int *)malloc(num*sizeof(int));
// allocate memory, and initialize memory
p=(int *)calloc(num,sizeof(int));
// reallocate memory
// ptr=null, behaves exactly as malloc
// size=0, behaves exactly as free, returns NULL
p=(int *)realloc(p,num*sizeof(int));
return 0;
}
malloc, free的实现
//TODO 可参考 the C programming language
Main之前与之后
#include <stdio.h>
struct A
{
A()
{puts("Before main.");}
~A()
{puts("After main.");}
};
A a;
int main()
{
puts("In main.");
return 0;
}
头文件ctype.h
isdigit, isxdigit, isalpha, isalnum的使用
好处:1.宏实现,速度快;2.移植性强。
数字与字符串之间的转换
数字->字符串:sprintf秒杀
字符串->数字:atoi, atol, atof, strtol。
多个strtol使用一起需要注意左结合还是右结合。
/* atoi example */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char *strI="-123";
printf("%d %d\n",atoi(strI),atol(strI));
char *strF1="-123.123";
char *strF2="-1e100";
printf("%lf %lf\n",atof(strF1),atof(strF2));
char *strMul="2001 60c0c0 -1101110100110100100000 0x6fffff";
char *pStr;
long int a=strtol(strMul,&pStr,10),
b=strtol(pStr,&pStr,16),
c=strtol(pStr,&pStr,2),
d=strtol(pStr,&pStr,0);
printf("%ld %ld %ld %ld\n",a,b,c,d);
return 0;
}
字符串、内存拷贝函数
strcpy:1.源和目的地址重叠,结果未定义。
strncpy:1.比strcpy安全;2.同strcpy1
memcpy:1.同strcpy1
memmove:1.源和目的地址重叠时,能正确处理
字符串比较
strcmp, strcasecmp忽略大小写
字符串连接
strcat, strncat:源和目的地址重叠,结果未定义
字符串、内存查找
strstr, strchr, strrchr, memchr
其他字符串操作函数
strdup复制字符串,注意free,不然会内存泄露
memset注意是以字节填入内存,value虽然类型为int,但是必须是unsigned char
标准预定义宏
#include <stdio.h>
int main()
{
printf("Current line number %d\n",__LINE__);
printf("Current source file name %s\n",__FILE__);
printf("Current Compile date %s\n",__DATE__);
printf("Current Compile time %s\n",__TIME__);
return 0;
}
断言assert
通过#define NDEBUG(需要在assert.h前)或者编译选项-DNDEBUG#include <stdio.h>
//#define NDEBUG // before inclusion of assert.h
#include <assert.h>
int main()
{
assert(true); // pass
assert(false); // can not pass
return 0;
}
宏# ##的用法
#include <stdio.h>
#define FUNC(x) func##x
#define PUT(x) puts(#x" "#x);
void func1()
{puts("fun1");}
void func2()
{puts("fun2");}
void func(const char *str)
{puts(str);}
int main()
{
FUNC(1)();
FUNC(2)();
PUT(abc);
return 0;
}
注释掉代码
int main()
{
#if 0
// code not being used here
#endif
return 0;
}