名称:
|
Malloc/calloc
|
功能:
|
动态内存分配函数
|
头文件:
|
#include
<stdlib
.h>
|
函数原形:
|
void *malloc(size_t size);
void *calloc(size_t num,size_t size);
|
参数
:
|
size 分配内存块的大小
num 分配内存块的个数
|
返回值:
|
成功返回分配内存块的首地址,失败返回NULL.
|
#include <stdio.h>
#include <stdlib.h>
main()
{
int *p=NULL;
p=(int *)malloc(sizeof(int));
if(p==NULL)
{
printf("malloc error/n");
exit(1);
}
*p=3;
printf("%d/n",*p);
free(p);
}
|
名称:
|
free
|
功能:
|
动态内存释放函数
|
头文件:
|
#include
<stdlib
.h>
|
函数原形:
|
void free(void *ptr);
|
参数
:
|
ptr 使用malloc或calloc等内存分配函数所返回的内存指针
|
返回值:
|
无
|
名称:
|
memset
|
功能:
|
初始化所指定的内存空间
|
头文件:
|
#include
<stdlib
.h>
|
函数原形:
|
void *memset(void *buffer,int c,int count);
|
参数
:
|
buffer 分配的内存
c 初始化内容
count 初始化的字节数
|
返回值:
|
返回指向buffer的指针
|
main()
{
int *p=NULL;
int i;
char *q=NULL;
p=(int *)malloc(sizeof(int)*10);
if(p==NULL)
exit(1);
memset(p,0,sizeof(int)*10);
q=p;
for(i=0;i<10;i++)
printf("%d",*(q++));
free(p);
}
|
名称:
|
memcpy
|
功能:
|
拷贝内存空间
|
头文件:
|
#include
<stdlib
.h>
|
函数原形:
|
void *memcpy(void *dest,void *src,unsigned int count);
|
参数
:
|
dest 目标内存区
src 原内存区
count 要复制的字节数
|
返回值:
|
指向dest的指针
|
main()
{
int *p1=NULL;
int *p2=NULL;
int q;
int i;
p1=malloc(sizeof(int)*10);
if(p1==NULL)
exit(1);
p2=malloc(sizeof(int)*5);
if(p2==NULL)
exit(1);
memset(p1,0,sizeof(int)*10);
memcpy(p2,p1,sizeof(int)*5);
q=p2;
for(i=0;i<5;i++)
printf("%d",*(q++));
free(p1);
free(p2);
)
|
名称:
|
memmove
|
功能:
|
拷贝(移动)内存空间
|
头文件:
|
#include
<stdlib
.h>
|
函数原形:
|
void *memmove(void *dest,void *src,unsigned int count);
|
参数
:
|
dest 目标内存区
src 原内存区
count 要复制的字节数
|
返回值:
|
指向dest的指针
|
名称:
|
memcmp
|
功能:
|
比较两个内存空间的字符
|
头文件:
|
#include
<stdlib
.h>
|
函数原形:
|
int memcmp(void *buf1,void *buf2,unsigned int count);
|
参数
:
|
buf1 内存区
buf2 内存区
count 要比较的字符数
|
返回值:
|
见下面
|
main()
{
int *p1=NULL;
int *p2=NULL;
int rt;
p1=malloc(sizeof(int)*10);
if(p1==NULL)
exit(1);
p2=malloc(sizeof(int)*10);
if(p2==NULL)
exit(1);
memset(p1,'a',sizeof(int)*10);
memset(p2,'b',sizeof(int)*10);
rt=memcmp(p1,p2,sizeof(int)*10);
if(rt>0)
printf("p1>p2);
if(rt<0)
printf("p1<p2");
if(rt==0)
printf("p1=p2");
free(p1);
free(p2);
}
|