当前位置:网站首页>动态内存开辟(C语言)
动态内存开辟(C语言)
2022-08-05 08:33:00 【InfoQ】
内存的三个区域

为什么要使用动态内存开辟
动态内存分配的函数
free
free(p);
p=NULL;
malloc
void* malloc (size_t size);打印错误原因的一种方式
#include<string.h>
#include<errno.h>
#include<stdio.h>
printf("%s\n",strerror(errno));
由malloc和free的实例演示
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
int main()
{
int* p = (int*)malloc(10 * sizeof(int));
if (p == NULL)
printf("%s\n", strerror(errno));
else
{
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));
}
}
free(p);
p = NULL;
return 0;
}

realloc
int* p = (int*)malloc(20);
int* p2 = realloc(p, 40);
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
int main()
{
int* p = (int*)malloc(20);
if (p == NULL)
{
printf("%s\n", strerror(errno));
}
else
{
int i = 0;
for (i = 0; i < 5; i++)
{
*(p + i) = i;
}
}
int* p2 = realloc(p, 40);
if (p2 != NULL)
{
p = p2; //把p2的首地址又给了p,做到了衔接
int i = 0;
for (i = 5; i < 10; i++)
{
*(p + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", *(p + i));
}
}
free(p);
p = NULL;
return 0;
}
边栏推荐
猜你喜欢

宝塔实测-搭建中小型民宿酒店管理源码

Chapter3、色调映射

MVCC of Google's Fragmented Notes (Draft)

spark集群部署(第三弹)

TensorFlow installation steps

egg框架中解决跨域的三种方案

DPU — 功能特性 — 网络系统的硬件卸载

How to make a puzzle in PS, self-study PS software photoshop2022, PS make a puzzle effect

uniapp时间组件封装年-月-日-时-分-秒
![[Structural Internal Power Cultivation] The Mystery of Enumeration and Union (3)](/img/39/d20f45ccc86ebc4e5aebc8e4d0115f.png)
[Structural Internal Power Cultivation] The Mystery of Enumeration and Union (3)
随机推荐
Thinking after writing a code with a very high CPU usage
iptables实现网络限制下ntp自定义端口同步时间
How to make pictures clear in ps, self-study ps software photoshop2022, simple and fast use ps to make photos clearer and more textured
The Coolest Kubernetes Network Solution Cilium Getting Started Tutorial
DataFrame在指定位置插入行和列
Nn. Unfold and nn. The fold
SVG大鱼吃小鱼动画js特效
程序设计中的感悟
撕裂寂寞
原型&原型链
动态库之间回调函数使用
sql server收缩日志的作业和记录,失败就是因为和备份冲突了吗?
ps怎么替换颜色,自学ps软件photoshop2022,ps一张图片的一种颜色全部替换成另外一种颜色
[NOIP2010 提高组] 机器翻译
Qt writes custom controls: one of the text spotlight effects
谷歌零碎笔记之MVCC(草稿)
The magic weapon for small entrepreneurs!
ps怎么拼图,自学ps软件photoshop2022,PS制作拼图效果
Luogu P1966: [NOIP2013 提高组] 火柴排队 [树状数组+逆序对]
DPU — 功能特性 — 管理系统的硬件卸载