stdlib.h

这篇博客通过示例代码介绍了C语言中stdlib.h库的一些常用函数,包括内存分配、随机数生成、环境变量操作、字符串转换以及排序算法等。主要函数包括malloc、calloc、realloc、free、rand、srand、atoi、atof、atol、getenv、qsort、bsearch等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值