C中malloc、calloc和realloc三个函数的区别
简短版(详细版附后)
malloc和calloc的区别:
1、参数个数不一样:
-
malloc一个参数,只需输入你要申请的大小*数据类型的大小
-
calloc两个参数,第一个为你要申请的大小,第二个参数为,所对应数据类型的大小。
2、是否初始化
-
malloc 不会初始化申请的空间
-
calloc会将申请的空间初始化为0
-
realloc和malloc、calloc的最大区别在参数
-
realloc主要作为扩容。第一个参数为->上一次申请空间时的返回值。
1、malloc
函数体:void *malloc(unsigned int num_size)
参数:计算出你要申请空间的大小
返回值:失败返回NULL,成功返回一个指针,指向已分配的内存。
2、calloc
函数体:void *calloc(size_t nitems, size_t size)
参数1:要被分配的元素个数;
参数2:所对应数据类型的大小;
返回值;如果请求失败,则返回 NULL,成功返回一个指针,指向已分配的内存。
3、realloc
函数体:void *realloc(void *ptr, size_t size);
参数1:指针指向上一次malloc\calloc或者realloc申请的空间。
参数2:内存块的新的大小,以字节为单位。
返回值:如果请求失败,则返回 NULL,成功返回一个指针,指向已分配的内存。
1、malloc函数的用法示例
#include <stdio.h>
#include <string.h>
#include <stdlib.h> //内存申请的头文件
int main()
{
char *str;
str = (char *) malloc(15);
strcpy(str, "runoob");
printf("String = %s, Address = %u\n", str, str);
/* 重新分配内存 */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}
2、calloc函数用法示例
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n;
int *a = NULL; //也可以写为int *a;
printf("要输入的元素个数:");
scanf("%d",&n);
a = (int*)calloc(n, sizeof(int));
printf("输入 %d 个数字:\n",n);
for( i=0 ; i < n ; i++ )
{
scanf("%d",&a[i]);
}
printf("输入的数字为:");
for( i=0 ; i < n ; i++ ) {
printf("%d ",a[i]);
}
free (a); // 释放内存
return(0);
}
3、realloc函数用法示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *str;
str = (char *) malloc(15);
strcpy(str, "runoob");
printf("String = %s, Address = %p\n", str, str);
/* 重新分配内存 */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %p\n", str, str);
free(str);
return(0);
}
3、拓展知识(数据结构动态顺序表中用到了扩容的思想)
//动态数据表
typedef struct list{
data_type(*Data)[];//存储空间,是一个数组指针
int size; //用来表示当前顺序表的大小
int count; //用来表示表里有多少元素
}List;
当size = count 时,就需要扩容,来存储更多的数据。