大小为 0 的数组 [英] Array with size 0

查看:35
本文介绍了大小为 0 的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天无意中定义了一个二维数组,一维的大小为0,但是我的编译器没有抱怨.我发现以下内容表明这是合法的,至少在 gcc 的情况下是这样:

Today I incidentally defined a two dimensional array with the size of one dimension being 0, however my compiler did not complain. I found the following which states that this is legal, at least in the case of gcc:

6.17 长度为零的数组

但是,我对这种用法有两个疑问:

However, I have two questions on this usage:

首先,这被认为是良好的编程习惯吗?如果是这样,那么我们什么时候应该在现实世界中使用它?

First, is this considered as good programming practice? If so, then when should we use it in real world?

第二,我定义的数组是二维的,一维大小为0.这和一维情况一样吗?例如,

Second, the array I defined was two dimensional, with 0 size for one dimension. Is this the same as the one dimensional case? For example,

int s[0]
int s[0][100]
int s[100][0]

它们在内存和编译器中都是一样的吗?

Are they all the same in the memory and for the compiler?

回复 Greg:我使用的编译器是 gcc 4.4.5.我对这个问题的意图与编译器无关,但是如果有任何特定于编译器的怪癖也会有帮助:)

Reply to Greg: The compiler I am using is gcc 4.4.5. My intention for this problem is not compiler-dependent, however if there are any compiler specific quirks that would be helpful too:)

提前致谢!

推荐答案

在 C++ 中声明零长度的数组是非法的.因此,当您将代码绑定到特定的编译器扩展时,它通常不被认为是一种好的做法.动态大小数组的许多用途最好用容器类代替,例如 std::vector.

In C++ it is illegal to declare an array of zero length. As such it is not normally considered a good practice as you are tying your code to a particular compiler extension. Many uses of dynamically sized arrays are better replaced with a container class such as std::vector.

ISO/IEC 14882:2003 8.3.4/1:

ISO/IEC 14882:2003 8.3.4/1:

如果constant-expression (5.19) 存在,它应该是一个整数常量表达式并且它的值应该大于零.

If the constant-expression (5.19) is present, it shall be an integral constant expression and its value shall be greater than zero.

但是,您可以使用 new[] 动态分配零长度的数组.

However, you can dynamically allocate an array of zero length with new[].

ISO/IEC 14882:2003 5.3.4/6:

ISO/IEC 14882:2003 5.3.4/6:

direct-new-declarator 中的表达式应具有非负值的整数或枚举类型 (3.9.1).

The expression in a direct-new-declarator shall have integral or enumeration type (3.9.1) with a non-negative value.

这篇关于大小为 0 的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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