当前位置:网站首页>Dynamic memory development (C language)
Dynamic memory development (C language)
2022-08-05 08:38:00 【InfoQ】
three regions of memory

Why use dynamic memory development
动态内存分配的函数
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; //把p2The first address was given againp,Connected
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;
}
边栏推荐
猜你喜欢

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

国际原子能机构总干事称乌克兰扎波罗热核电站安全形势堪忧

数据源对象管理Druid和c3p0

让程序员崩溃的N个瞬间(非程序员误入)

The Coolest Kubernetes Network Solution Cilium Getting Started Tutorial

Jmeter永久设置中文界面

D2--FPGA SPI interface communication2022-08-03

ps怎么把图片变清晰,自学ps软件photoshop2022,简单快速用ps让照片更清晰更有质感

苹果官网商店新上架Mophie系列Powerstation Pro、GaN充电头等产品

工程制图直线投影练习
随机推荐
爱情是一部忧伤的乐曲
长期招聘嵌入式开发-深圳宝安
DataFrame在指定位置插入行和列
Luogu P3368: 【模板】树状数组 2
egg framework
撕裂寂寞
Nn. Unfold and nn. The fold
原型&原型链
MySQL 数据库 报错 The server quit without updating PID file (/var/lib/mysql/localhost.localdomain.pid)
Version number naming convention
Codeforce 8.1-8.7做题记录
512色色谱图
动态库之间回调函数使用
高效使用数码相机的诀窍
MVCC of Google's Fragmented Notes (Draft)
Random code generation
Luogu P1966: [NOIP2013 提高组] 火柴排队 [树状数组+逆序对]
CROS和JSONP配置
[Repost] Marry a man must marry a man whose salary is at least 3571.4 yuan higher than yours
国际原子能机构总干事称乌克兰扎波罗热核电站安全形势堪忧