C++???????????????
???????????? ???????[ 2012/12/17 10:20:31 ] ????????
????C99?н??е??????????δ???С???????????????????????????е????????????????????????????????????????????????а??????????С?????顣???????sizeof?????С????????????????檔???????????????????malloc??????涯??????????????????????????С???????????????????С?? — ????C????????
????????????????????????£?
#include <stdio.h>
// ??????????????
typedef struct StType {
int count;
int item[0];
} StType;
int main()
{
printf("sizeof(StType) = %d
"?? (int)sizeof(StType));
int val[4] = {3?? 1?? 2?? 3};
StType *st = (StType*)val;
for (int i = 0; i < st->count; i++)
printf("%d value =%d
"?? i?? st->item[i]);
return 0;
}
????????????н?????£?
sizeof(StType) = 4
0 value = 1
1 value = 2
2 value = 3
????????????????????item[0]????????????????????????malloc????new?????б????????????????
StType*st=(StType*)newchar[sizeof(StType)+100*sizeof(int)];
st.count=100;
delete[]st;
???????????????????100??item??StType???????????delete[]st;?????????檔
???????????????????Fleiblearray member????C89??????????C99??????????????????У?????C99????????????????????????0???飬???int item[0];?????????????????int item[]?????????Щ??????????????????????????int item[0]?????????????
?????????VC?б????????澯????????£?
warning C4200: nonstandard extension used :zero-sized array in struct/union
Cannot generate copy-ctor orcopy-assignment operator when UDT contains a zero-sized array
??????????? C99??????“???????”??
????C89 ????漲???????С??????????????????????C99 ?У????????????????????????????????????????????????? C++ ??????й??????????? C99 ?????????????飬??????? C99 ?? C ????????
??????????????????????????????????????????????????????????鯔????????????????????С??
??????????????????????????????????????????????????б??C89???????????????????м????????????????
????1??????1
struct header {
size_t len;
unsigned char data[1];
};
ptr = malloc(sizeof(struct header) + (n -1));
??????????????????Ч??????????????????????????????
????2??????2
struct header*my_header = malloc(offsetof(struct header?? data)
+ n * sizeof(my_header->data));
??????????ú?????????
#define FLEXIBLE_SIZE SIZE_MAX // or whatever maximum length for an array
#defineSIZEOF_FLEXIBLE(type?? member?? length)
(offsetof(type??member) + (length) * sizeof((type*)0)->member[0])
?????????????????????????????C89?????????????????????????????????????C99????????????????????????
????3??????3
????????????????????μ????????????????????????????
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11