动态内存管理之柔性数组

#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次数越多,形成内存碎片的几率越大

相关推荐
PAK向日葵1 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱装代码的小瓶子2 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
爱喝矿泉水的猛男3 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao3 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
YouQian7724 小时前
Traffic Lights set的使用
算法
go54631584655 小时前
基于深度学习的食管癌右喉返神经旁淋巴结预测系统研究
图像处理·人工智能·深度学习·神经网络·算法
aramae5 小时前
大话数据结构之<队列>
c语言·开发语言·数据结构·算法
大锦终5 小时前
【算法】前缀和经典例题
算法·leetcode
想变成树袋熊6 小时前
【自用】NLP算法面经(6)
人工智能·算法·自然语言处理
cccc来财6 小时前
Java实现大根堆与小根堆详解
数据结构·算法·leetcode