malloc realloc calloc

三个函数大多使用在c语言函数的指针当中为指针分配地址,他们的原型分别如
下:
void *realloc(void *ptr,unsigned newsize);
void *malloc(unsigned size);
void *calloc(num,unsigned size);
他们包含在stdlib.h的函数里,一般使用sizeof()函数分配size的大小。

1)malloc用于申请一段新的地址,size为所需空间的长度;
例子如下:
#include<stdio.h>
#include<stdlib.h>
int main()
{
 char *num;
 num=(char *)malloc(sizeof(char));
 if(num)
 printf("恭喜你已成功为num分配了地址\n");
 else
 printf("抱歉,分配失败\n");
 return 0;
}

2)calloc的用法与malloc的差别不是太大,就是多了一个num,num表示申请地址
元素的个数,unsigned size代表分配空间的长度。
例子如下:
#include<stdio.h>
#include<stdlib.h>
int main()
{
 char *num;
 num=(char *)calloc(20,sizeof(char));
 if(num)
 printf("恭喜你已成功为num分配了能存储20个元素的地址\n");
 else
 printf("抱歉,分配失败\n");
 return 0;
}
3)realloc指的是为已经分配了地址的指针重新分配空间,unsigned size指的是重新
分配的空间。其中重新分配的长度必须大于以前的长度
例子如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
 char *num,*num1;
 num1=num=(char *)calloc(20,sizeof(char));
 num=(char *)realloc(num,sizeof(char));
 if(num)
 printf("恭喜你已经成功为num重新分配了地址\n");
 else
 printf("抱歉,分配失败\n");
 return 0;
}

原文地址:https://www.cnblogs.com/xiohao/p/3031837.html