C中malloc、calloc和realloc三个函数的区别

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 时,就需要扩容,来存储更多的数据。

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牲码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值