柚子快報邀請碼778899分享:【C語言】還有柔性數(shù)組?
柚子快報邀請碼778899分享:【C語言】還有柔性數(shù)組?
前言
也許你從來沒有聽說過柔性數(shù)組(flexible array)這個概念,但是它確實是存在的。C99中,結(jié)構(gòu)中的最后?個元素允許是未知??的數(shù)組,這就叫做『柔性數(shù)組』成員。
歡迎關(guān)注個人主頁:逸狼
創(chuàng)造不易,可以點點贊嗎~
如有錯誤,歡迎指出~
目錄
前言
柔性數(shù)組
柔性數(shù)組的特點
柔性數(shù)組的使用
不使用柔性數(shù)組
柔性數(shù)組
如下代碼int a[0]就是柔性數(shù)組
struct st_type
{
int i;//柔性數(shù)組前面至少要有一個其他成員
int a[0];//柔性數(shù)組成員
//int a[];
};
柔性數(shù)組的特點
結(jié)構(gòu)中的柔性數(shù)組成員前?必須?少?個其他成員。sizeof返回的這種結(jié)構(gòu)??不包括柔性數(shù)組的內(nèi)存。包含柔性數(shù)組成員的結(jié)構(gòu)?malloc()函數(shù)進?內(nèi)存的動態(tài)分配,并且分配的內(nèi)存應(yīng)該?于結(jié)構(gòu)的??,以適應(yīng)柔性數(shù)組的預(yù)期??。
柔性數(shù)組的使用
使用柔性數(shù)組,只是用了一次malloc函數(shù),有利于訪問速度(相對而言),減少了內(nèi)存碎片把結(jié)構(gòu)體的內(nèi)存以及其成員要的內(nèi)存?次性分配好,并返回?個結(jié)構(gòu)體指針,?次free就可以把所有的內(nèi)存也給釋放掉。
struct st
{
int a;
int arr[];
};
int main()
{//用結(jié)構(gòu)體指針變量ps接收malloc函數(shù)分配空間的地址
struct st*ps=(struct st*)malloc(sizeof(struct st) + 10 * sizeof(int));
// malloc分配空間的大小是 結(jié)構(gòu)體大小+40字節(jié) (40字節(jié)是分配給柔性數(shù)組的)
//判斷
if (ps == NULL)
{
return 1;
}
//使用
ps->a = 100;
for (int i = 0; i < 10; i++)
{
ps->arr[i] = i;
}
//若數(shù)組空間不夠
//用realloc函數(shù)重新分配
struct st*ptr=(struct st*)realloc(ps,sizeof(struct st) + 15 * sizeof(int));
if (ptr != NULL)
{
ps = ptr;//再次賦值給ps
}
else
{
perror("realloc");
}
//繼續(xù)使用
for (int i = 0; i < 15; i++)
{
ps->arr[i] = i;
}
//打印
for (int i = 0; i < 15; i++)
{
printf("%d ",ps->arr[i]);
}
//釋放
free(ps);
ps = NULL;
return 0;
}
對比 不使用柔性數(shù)組
不使用柔性數(shù)組實現(xiàn)同樣功能,就要多次使用malloc函數(shù)開辟空間
#include
#include
struct st
{
int a;
int* arr;
};
int main()
{//用結(jié)構(gòu)體指針變量ps接收malloc函數(shù)分配空間的地址
struct st* ps = (struct st*)malloc(sizeof(struct st));
//判斷
if (ps == NULL)
{
return 1;
}
//使用
ps->a = 100;
//再次使用malloc函數(shù)給數(shù)組arr開辟空間
ps->arr = (int*)malloc(10 * sizeof(int));
if (ps->arr == NULL)
{
perror("malloc-2");
return 1;
}
//使用
for (int i = 0; i < 10; i++)
{
ps->arr[i] = i;
}
//數(shù)組空間不夠
// 利用realloc函數(shù)擴大
int* ptr = (int*)realloc(ps->arr, 15 * sizeof(int));
if (ptr == NULL)
{
perror("realloc");
return 1;
}
else
{
ps->arr = ptr;
}
//初始化前15個元素
for (int i = 0; i < 15; i++)
{
ps->arr[i] = i;
}
//打印
for (int i = 0; i < 15; i++)
{
printf("%d ", ps->arr[i]);
}
//釋放
free(ps->arr);
ps->arr = NULL;
free(ps);
ps = NULL;
return 0;
}
柚子快報邀請碼778899分享:【C語言】還有柔性數(shù)組?
文章來源
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。