Re: array of zero elements



On Feb 17, 3:26 pm, George <Geo...@xxxxxxxxxxxxxxxxxxxxxxxxx> 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];
}

Since the zero size member is in there, there are few restrictions as
well. You cannot create an array of the test struct. You can mimic
that though like this:

//create an array of length 10 of test pointers
test * ptr[10];
//set each of the pointers to individual elements created as above

Generally, you would be better off keeping a pointer member but it is
worth noting the presence of such an extension. See for details :
http://msdn2.microsoft.com/en-us/library/ms858712.aspx
.



Relevant Pages

  • Re: array of zero elements
    ... I have tested in Visual Studio 2008 the initialization of aa works. ... we allocate array of zero elements. ... int buf; ...
    (microsoft.public.vc.language)
  • Re: array of zero elements
    ... still using the standard language. ... we allocate array of zero elements. ... int buf; ...
    (microsoft.public.vc.language)
  • Re: array of zero elements
    ... still using the standard language. ... we allocate array of zero elements. ... int buf; ...
    (microsoft.public.vc.language)
  • Re: Safest way to convert chars to ints
    ... Having allocated an array like this, you should ideally dispose of it. ... I don't see that it is really necessary to set each element to zero the ... 'i' an 'int' for sscanf to work properly. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: array of zero elements
    ... we allocate array of zero elements. ... int buf; ...
    (microsoft.public.vc.language)

Loading