Array of classes - new MyClass[0];

When I do a new MyClass[val] where val can also be 0 then what is the expected output. Can this throw an exception ?
There is nothing wrong with declaring an array of zero length.
Actually I take that back. Zero length arrays are non-standard. I learn something new every day ;o)
Last edited on
Galik, I find that a little surprising, too...

How would you use a zero length array to good affect?

Googling around, I can't find a good use for this!
How would you use a zero length array to good affect?


You wouldn't. I'm guessing it's a lame attempt to save testing val against 0 before creation.
Actually its an old C trick for defining structs that have a variable amount of data appended to their header:
1
2
3
4
5
6
7
struct header
{
    int data_size;
    char type;
    int id;
    char data[0];
};

This allows you to index data that comes after the struct header like this:
1
2
3
4
// The zero sized dimension ensures the sizeof(struct header) does not include any data
struct header* h = (struct header*) malloc(sizeof(struct header) + data_size);

h.data[24] = 'x'; // Now write data beyond the end of the header. 


I always assumed it was legal. Now I think that you should leave the dimension blank:

1
2
3
4
5
6
7
struct header
{
    int data_size;
    char type;
    int id;
    char data[]; // no size specified
};

Last edited on
Very interesting!

All you really care about is the position/address at the end of the struct:
1
2
char* cptr = &h.data;
*(cptr+24) = 'x';

With char data[] or char data[0] in there, would sizeof( header ) be the same with the data field missing?

If that's the case, data would really just act like a marker...
kfmfe04 wrote:
With char data[] or char data[0] in there, would sizeof( header ) be the same with the data field missing?

Yes. That's the point of doing it that way. Even a size 1 element array will alter the header size.

On GCC all these give the same sizeof(header) as 4:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct header
{
	int i;
	char data[0];
};

struct header
{
	int i;
	char data[];
};

struct header
{
	int i;
};
It's like an old Jedi mind trick (v.nice!) ty for explaining.
Indeed. C programming used to be quite a dark art, verging on the occult. ;o)
Topic archived. No new replies allowed.