Array of size 0 | Sololearn: Learn to code for FREE!


Array of size 0

How to explain this behavior in code? Why we can declare array with zero size?

4/14/2018 1:24:44 AM

Rull Deef 🐺

4 Answers

New Answer


Check out this discussion here on this very topic: Compiling it on my machine with the flag -pedantic (I used g++ -pedantic test.cpp), I get the following warning: test.cpp:10:13: warning: zero size arrays are an extension [-Wzero-length-array] int arr[0]; The standards also seem to say that it shouldn't really be allowed.


You should know line 11 is overwriting something as arr[0] doesn't allocate storage. I can't tell why it is allowed, but since C++ doesn't verify index out of bounds, I can give you a use for it. Declare a structure with it that you allocate on heap with valid extra storage. struct Array { int size; int storage[0]; } *array; array = maloc(sizeof(int)*(n+1)); array->size = n; for (int i = 0; i < n; i++) array->storage[i] = i;


Thanks a lot


You can do this because you will likely dynamically add data to that array through your program, via an API, or via I/O hooked up to a machine running your program. You can think if an array as a container to store information