網站首頁 編程語言 正文
柔性數組概念:
柔性數組就是一種特殊的數組
它也是結構體最后一個成員
也就是說,它存在結構體最后一個成員的位置上
特點:
1.柔性數組在結構體的大小是未知的,在sizeof中不計算其大小
#include<stdio.h> struct S { int n ; int arr[0];//或者int arr[]; }; main() { printf("The size of the structure is %d",sizeof(struct S)); return 0; }
2.在結構體中,如果存在柔性數組,就必須滿足它的前面含有其它的成員,來申請空間,,因為他的大小本身是未知的,不計算大小。
3.包含柔性數組的結構體要靠malloc去動態申請這塊空間,這就體現了柔性數組的柔,也就是可以控制大小,且分配的空間一定滿足大于其它成員的大小。
與指針動態開辟的比較
在日常的編程中,有時候需要在結構體中存放一個長度動態的數組
一般的做法,是在結構體中定義一個指針成員,這個指針成員指向該數組所在的動態內存空間
指針動態開辟
#include<stdio.h> struct S { int n; int* arr; }; int main() { struct S* ps = (struct S*)malloc(sizeof(struct S)); ps->n = 100; ps->arr = (int*)malloc(40); free(ps->arr); ps->arr = NULL; free(ps); ps = NULL; return 0; }
通過柔性數組來實現如下:
柔性數組
#include<stdio.h> struct S { int n; int arr[0];//柔性數組 }; int main() { struct S* ps = (struct S*)malloc(sizeof(struct S)+40); //使用 //改變申請的空間 struct S* tmp= (struct S*)realloc(ps, sizeof(struct S)+80); if (tmp == NULL) { return; } if (tmp != NULL) { ps = tmp; } return 0; }
?
指針動態開辟的缺點
1.此方式會多次進行開辟于釋放動態申請的空間,就容易會導致錯誤
2.容易出現內存碎片
當指針動態開辟的足夠多的時候,中間就會出現很多內存碎片,每個內存碎片不連續
就會導致空間的浪費
3.相較于柔性數組,CPU訪問的速度要慢一些
CPU訪問內存大部分在訪問一個空間后,就會訪問相鄰的空間,就不一次性訪問下一個連續的空間,這就會導致,在一定程度上的降速。?
總結
原文鏈接:https://blog.csdn.net/m0_64332179/article/details/122953630
相關推薦
- 2023-05-11 SQL?多表聯合查詢的幾種方式詳解_MsSql
- 2022-10-06 詳解hive常見表結構_數據庫其它
- 2022-10-18 EasyUI使用DataGrid實現動態列數據綁定_jquery
- 2022-04-09 Android項目中gradle的執行流程_Android
- 2022-07-22 TypeError: this.getOptions is not a function 的解決
- 2022-05-12 Android 截屏實現、屏幕截圖、MediaProjection、ImageReader
- 2023-09-17 POM文件中使用<exclusions>解決jar沖突問題
- 2022-10-14 eclipse創建maven項目
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支