当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

Pagoda measurement - building small and medium-sized homestay hotel management source code

Support touch screen slider carousel plugin

Adb 授权过程分析

The Coolest Kubernetes Network Solution Cilium Getting Started Tutorial

最 Cool 的 Kubernetes 网络方案 Cilium 入门教程

v-if/v-else determines whether to display according to the calculation

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

力扣刷题八月第一天

D2--FPGA SPI interface communication2022-08-03

DNS 查询原理详解
随机推荐
egg framework
嵌入式系统:基本定时器
Qt writes custom controls: one of the text spotlight effects
Luogu: P2574 XOR的艺术 [线段树]
[Structural Internal Power Cultivation] Structural Realization Stages (2)
ps怎么把图片变清晰,自学ps软件photoshop2022,简单快速用ps让照片更清晰更有质感
Fiddler工具讲解
Linux导出数据库数据到硬盘
DataFrame insert row and column at specified position
SVG Star Wars Style Toggle Toggle Button
Luogu P1966: [NOIP2013 提高组] 火柴排队 [树状数组+逆序对]
微信小程序请求封装
复现一次循环和两次循环
DataFrame在指定位置插入行和列
Chapter 12 贝叶斯网络
Controller-----controller
Ethernet Principle
动态内存开辟(C语言)
按钮上显示值的轮流切换
MySQL database error The server quit without updating PID file (/var/lib/mysql/localhost.localdomain.pid)