欢迎来到天天文库
浏览记录
ID:10210787
大小:25.50 KB
页数:3页
时间:2018-06-12
《内存分配函数举例》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、函数名:malloc功 能:内存分配函数用 法:void*malloc(unsignedsize);程序例:#include#include#include#includeintmain(void){ char*str; /*allocatememoryforstring*/ /*Thiswillgenerateanerrorwhencompiling*/ /*withC++,usethenewoperatorinstead.*/ if((str=malloc(10))==NULL) { printf("Notenoughmemorytoallocatebuffer")
2、; exit(1); /*terminateprogramifoutofmemory*/ } /*copy"Hello"intostring*/ strcpy(str,"Hello"); /*displaystring*/ printf("Stringis%s",str); /*freememory*/ free(str); return0;}函数名:calloc功 能:分配主存储器用 法:void*calloc(size_tnelem,size_telsize);程序例:#include#includeintmain(void){ char*str=NULL;
3、 /*allocatememoryforstring*/ str=calloc(10,sizeof(char)); /*copy"Hello"intostring*/ strcpy(str,"Hello"); /*displaystring*/ printf("Stringis%s",str); /*freememory*/ free(str); return0;}函数名:free功 能:释放已分配的块用 法:voidfree(void*ptr);程序例:#include#include#includeintmain(void){ char*str; /*allocat
4、ememoryforstring*/ str=malloc(10); /*copy"Hello"tostring*/ strcpy(str,"Hello"); /*displaystring*/ printf("Stringis%s",str); /*freememory*/ free(str); return0;}
此文档下载收益归作者所有