动态内存管理之柔性数组

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

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

//

//typedef struct

//{

// int n;

// int arr[0];//这里的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->arr[i] = i;

// }

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

// {

// printf("%d ", ps -> arr[i]);

// }

// 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->arr[i] = i;

printf("%d", ps->arr[i]);

}

//扩容

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

if (ptr == NULL)

{

return 1;

}

//释放

free(ps ->arr);

free(ps);

ps = NULL;

return 0;

}

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

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

相关推荐
挺菜的5 分钟前
【算法刷题记录(简单题)003】统计大写字母个数(java代码实现)
java·数据结构·算法
mit6.8245 分钟前
7.6 优先队列| dijkstra | hash | rust
算法
2401_8582861139 分钟前
125.【C语言】数据结构之归并排序递归解法
c语言·开发语言·数据结构·算法·排序算法·归并排序
guygg881 小时前
基于matlab的FIR滤波器
开发语言·算法·matlab
双叶8362 小时前
(C++)学生管理系统(正式版)(map数组的应用)(string应用)(引用)(文件储存的应用)(C++教学)(C++项目)
c语言·开发语言·数据结构·c++
ysh98882 小时前
PP-OCR:一款实用的超轻量级OCR系统
算法
遇雪长安2 小时前
差分定位技术:原理、分类与应用场景
算法·分类·数据挖掘·rtk·差分定位
数通Dinner2 小时前
RSTP 拓扑收敛机制
网络·网络协议·tcp/ip·算法·信息与通信
张人玉4 小时前
C# 常量与变量
java·算法·c#
学不动CV了4 小时前
数据结构---链表结构体、指针深入理解(三)
c语言·arm开发·数据结构·stm32·单片机·链表