#include
#include
#include
//测试内存分配
void testmem();
//测试随机数
void testrand();
//测试环境变量
void testenv();
//测试字符串转化
void testchar();
//测试system abort exit
void testthree();
//测试2分查找
int comp(const void *p1, const void *p2);
void testbsearch();
//测试qsort
void testqsort();
int main()
{
testqsort();
//testbsearch();
testthree();
//testchar();
//testenv();
//testrand();
//testmem();
return 0;
}
int comp(const void *p1, const void *p2)//注意参数格式
{
return (*(int *)p1 - *(int *)p2);
}
void testqsort()
{
int arr[5] = {421,103,89,213,47};
int i;
qsort(arr,5,sizeof(int),comp);
for(i=0; i<4; i++)
printf("%d ",arr[i]);
printf("%d\n",arr[i]);
}
void testbsearch()
{
int arr[5] = {47,89,103,213,421};//有序数组
int *i,key;
key = 89;
i = (int *)bsearch(&key,arr,5,sizeof(int),comp);
printf("i = %d\n",*i);
}
void testthree()
{
printf("began to exec\n");
system("clear");//清屏
abort();//终止exit(0)
printf("end will not exec\n");
}
void testchar()
{
int i,ppos,sign;
double d;
long l;
char *str,tmp[10];
//字符串转数字
i = atoi("123");
printf("%d\n",i);
d = atof("15.56");
printf("%2.2lf\n",d);
l = atol("32769");
printf("%ld\n",l);
//数字转字符串
d = -678.7654;
gcvt(d,6,tmp);//注意这里的tmp必须分配空间,6不包括小数点和符号
printf("%s\n",tmp);
str = fcvt(d,2,&ppos,&sign);//sign=0表示正数1为负数 ppos为小数点位置 2表示保留两位小数(四舍五入)
printf("%s %d %d\n",str,ppos,sign);
ecvt(d,6,&ppos,&sign);//整体保留6位(不算符号,包括小数点) sign=0表示正数非0负数
printf("%s %d %d\n",str,ppos,sign);
}
void testenv()
{
char *val;
putenv("MYSELF=hello");
val = getenv("MYSELF");
printf("%s\n",val);
}
void testrand()
{
int r,i;
i = 0;
srand((int)time(0));//设置随机数种子
while(i < 10)
{
r = 1 + (int)(10.0*rand()/(RAND_MAX+1.0));
printf("%d\n",r);
i++;
}
}
void testmem()
{
char *str;
str = malloc(sizeof(char)*6);
str[0] = 'h';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = 0;
printf("%s1\n",str);
free(str);
str = calloc(6,sizeof(char));
str[0] = 'h';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = 0;
printf("%s2\n",str);
free(str);
//realloc重新分配空间,可以变大可以缩小
str = calloc(6,sizeof(char));
str = realloc(str,12);
str[0] = 'h';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = ' ';
str[6] = 'w';
str[7] = 'o';
str[8] = 'r';
str[9] = 'l';
str[10] = 'd';
str[11] = 0;
printf("%s\n",str);
free(str);
}
stdlib.h
最新推荐文章于 2020-07-01 16:51:38 发布