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

问题描述

今天,我顺便定义的一维是0大小的二维数组,但是我的编译器并没有抱怨。我发现其中指出,这是合法的,至少在海湾合作委员会的情况下,以下内容:

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?

编辑:回复格雷格:我使用的编译器是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 ++中是非法的声明长度为零的数组。因此,它通常不认为是你绑你的code到一个特定的编译器扩展一个很好的做法。动态调整阵列的许多用途更好地与容器类代替,如的std ::矢量

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:

如果在恒前pression 的(5.19)是present,它应是一个整型常量前pression其值应大于零。

不过,您可以动态地分配零长度的数组与新[]

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:

直接新的说明符的前pression 的应具有与非负值整数或枚举类型(3.9.1)。

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

07-30 17:08