+ 7
Array of size 0
How to explain this behavior in code? Why we can declare array with zero size? https://code.sololearn.com/c94qBa12TtpV/?ref=app
4 Answers
+ 4
Check out this discussion here on this very topic:
https://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size-array-in-c-c
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.
+ 6
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;
+ 5
Thanks a lot
- 1
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