On Feb 17, 3:26 pm, George <Geo...@discussions.microsoft.com>
wrote:
Hello everyone,
Sometimes, we allocate array of zero elements. I am wondering for
what regualr purpose will we do that?
It is valid so that you can have code like this:
void f(size_t n)
{
int * ptr = new int[n];
//...
delete[] ptr;
}
instead of:
void f(size_t n)
{
if (n>0)
{
int * ptr = new int[n];
//...
delete[] ptr;
}
}
No other use though, because since it has zero elements, you
cannot do anything with it.
That would not mean that there is no use of zero sized (or better
say 'unsized') arrays. VC++ has an extension which makes use of
zero sized arrays as the last member of structures. For example,
see this:
#include<cstdlib>
#include<iostream>
struct test
{
int cb;
int buf[];
};
int main()
{
test* bb;
int length = 10;
bb = (test*) malloc(sizeof(test)+sizeof(int)*length);
bb->cb = length;
//fill buf with length int items or can copy from another array
for length elements
bb->buf[i]=10; //i should be less than length
//OR--------
test aa = {10, {1,10,22,32}};
std::cout << aa.buf[2];
}
std::vector does for C++. I don't think the aa initialization
works either.