动态内存管理之柔性数组

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

//C99中,结构中最后一个元素允许是未知大小的数组,这就叫做柔性数组成员

//

//typedef struct

//{

// int n;

// int arr0;//这里的a就是柔性数组成员

//}type_a;

//int main()

//{

// //柔性数组的特点

// // 计算结构体大小时,只计算柔性数组前的成员的大小

// //

// int sz = sizeof(type_a);

// printf("%d", sz);

// //包含柔性数组的结构体,应使用malloc去开辟内存空间,并且开辟空间的大小要大于柔性数组的大小

// //柔性数组的使用

// type_a* ps = (type_a*)malloc(sizeof(type_a)+40);

// //其他成员的大小,以及给柔性数组成员的空间

// if (ps == NULL)

// {

// return 1;

// }

// ps -> n = 100;

// int i = 0;

// for (i = 0;i < 10;i++)

// {

// ps->arri = i;

// }

// for (i = 0;i < 10;i++)

// {

// printf("%d ", ps -> arri);

// }

// type_a* ptr = (type_a*)realloc(ps, 80);

// if (ptr != NULL)

// {

// ps = ptr;

// ptr = NULL;

// }

// free(ps);

// ps = NULL;

// return 0;

//}

struct S

{

int n;

int* arr;

};

int main()

{

struct S* ps = (struct S*)malloc(40);

if (ps == NULL)

{

return 1;

}

ps->n = 100;

ps->arr = (int*)malloc(40);

if (ps->arr == NULL)

{

return 1;

}

//使用

int i = 0;

for (i = 0;i < 10; i++)

{

ps->arri = i;

printf("%d", ps->arri);

}

//扩容

int* ptr = (int*)realloc(ps -> arr, 100);

if (ptr == NULL)

{

return 1;

}

//释放

free(ps ->arr);

free(ps);

ps = NULL;

return 0;

}

//使用柔性数组,则内存使用连续,读写速度更快

//malloc次数越多,形成内存碎片的几率越大

相关推荐
在所不辞兄28 分钟前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
郝学胜-神的一滴4 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
AvocadoZeroOneOI5 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
cjz38997 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
console.log('npc')9 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
橘子1310 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘21 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David1 天前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
Pniubi1 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展