51—动态内存管理

51.动态内存管理

1.malloc

#include <stdio.h>
#include <malloc.h>
int main()
{
	int len;
	int i,b;
	int * p = (int *)malloc(4 * len);
	printf("请输入数组个数:");
	scanf("%d",&len);
	printf("请输入要存储的数字:");
	for( i=0;i<len;i++){
	scanf("%d",&p[i]);
	}
	for( b=0;b<len;b++){
	printf("%d\n",p[b]);
	}
	free(p);
	return 0;
}

2.calloc

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(void)
{
	int i;
	int *p = (int *)calloc(10, sizeof(int));
	for (i = 0; i < 10; i++)
	{
		printf("%3d", p[i]);
	}
	printf("\n");
	free(p);
	getch();
	return 0;
}

3.realloc

#include <stdio.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);
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值