Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array with size 0 [duplicate]

Tags:

c++

arrays

c

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 Arrays of Length Zero

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?

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?

EDIT: 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:)

Thanks in advance!

like image 628
zw324 Avatar asked May 30 '11 19:05

zw324


2 Answers

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:

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

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

ISO/IEC 14882:2003 5.3.4/6:

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

like image 159
CB Bailey Avatar answered Oct 05 '22 22:10

CB Bailey


I ran this program at ideone.com

#include <iostream>  int main() {     int a[0];     int b[0][100];     int c[100][0];      std::cout << "sizeof(a) = " << sizeof(a) << std::endl;     std::cout << "sizeof(b) = " << sizeof(b) << std::endl;     std::cout << "sizeof(c) = " << sizeof(c) << std::endl;      return 0; } 

It gave the size of all the variables as 0.

sizeof(a) = 0 sizeof(b) = 0 sizeof(c) = 0 

So in the above example, no memory is allocated for a, b or c.

like image 45
Node Avatar answered Oct 05 '22 21:10

Node