Is there any way for a compound literal to have variable length in c99?

霸气de小男生 提交于 2019-12-10 16:24:20

问题


I know that arrays with lengths determined at runtime are possible by declaring the array normally:

char buf[len];

and I know that I can declare an array as a compound litral and assign it to a pointer midway:

char *buf;
....
buf = (char[5]) {0};

However, combining the two doesn't work (is not allowed by the standard).

My question is: Is there any way to achieve the effect of of the following code? (note len)

char *buf;
....
buf = (char[len]) {0};

Thank you.


回答1:


The language explicitly prohibits this

6.5.2.5 Compound literals

Constraints

1 The type name shall specify an object type or an array of unknown size, but not a variable length array type.

If you need something like this, you'd have to use a named VLA object instead of compund literal. However, note that VLA types do not accept initializers, meaning that you can't do this

char buf[len] = { 0 }; // ERROR for non-constant `len`

(I have no idea what the rationale behind this restriction is.)

So, in addition to using a named VLA object you'll have to come up with some way to zero it out, like a memset or an explicit cycle.



来源:https://stackoverflow.com/questions/14550557/is-there-any-way-for-a-compound-literal-to-have-variable-length-in-c99

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!