零长度数组 [英] Array of zero length
问题描述
我正在重构一些旧代码,发现很少有包含零长度数组的结构(如下).警告当然会被 pragma 压抑,但我未能通过包含此类结构的新"结构创建(错误 2233).数组byData"用作指针,但为什么不改用指针?或长度为 1 的数组?当然,没有添加任何评论来让我享受这个过程......使用这种东西的任何原因?在重构这些方面有什么建议吗?
I am working on refactoring some old code and have found few structs containing zero length arrays (below). Warnings depressed by pragma, of course, but I've failed to create by "new" structures containing such structures (error 2233). Array 'byData' used as pointer, but why not to use pointer instead? or array of length 1? And of course, no comments were added to make me enjoy the process... Any causes to use such thing? Any advice in refactoring those?
struct someData
{
int nData;
BYTE byData[0];
}
注意是 C++、Windows XP、VS 2003
NB It's C++, Windows XP, VS 2003
推荐答案
是的,这是一个 C-Hack.
创建任意长度的数组:
Yes this is a C-Hack.
To create an array of any length:
struct someData* mallocSomeData(int size)
{
struct someData* result = (struct someData*)malloc(sizeof(struct someData) + size * sizeof(BYTE));
if (result)
{ result->nData = size;
}
return result;
}
现在你有一个 someData 对象,它有一个指定长度的数组.
Now you have an object of someData with an array of a specified length.
这篇关于零长度数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!