有什么方法可以使复合文字在c99中具有可变长度? [英] Is there any way for a compound literal to have variable length in c99?

查看:95
本文介绍了有什么方法可以使复合文字在c99中具有可变长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道通过正常声明数组,可以在运行时确定长度的数组:

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).

我的问题是:有什么方法可以实现以下代码的效果? (请注意len)

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

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

谢谢.

推荐答案

该语言明确禁止这样做

6.5.2.5复合文字

约束

1 类型名称应指定对象类型或未知数组 大小,但不是可变长度的数组类型.

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

如果您需要类似的内容,则必须使用命名的VLA对象而不是compund文字.但是,请注意,VLA类型不接受初始化程序,这意味着您不能这样做

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.)

因此,除了使用命名的VLA对象之外,还必须想出一些方法将其归零,例如memset或显式循环.

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.

这篇关于有什么方法可以使复合文字在c99中具有可变长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆