why arrary with size of zero?

M

Mockey Chen

I saw some library code wrote like this:

struct X{
int x;
char y[0]; /* Note: here array size is ZERO, why? */
};


Why use array size zero. I heard about the C standard
not allow array with size zero, but my gcc tell me I can
compile this code without error or warning.

One give me explaination this trick can used for dynamic
memory, for example:
size_t bufsize;
...
struct X* px = NULL;
px = (struct X*)malloc(sizeof(struct X) + bufsize);
in this way, we can gain a X and additional bufsize in once
malloc invoke. Does this correct?

Another question is whether this code portable?

Any help is appreciated.

--
Regards.
Mockey Chen
Email: (e-mail address removed)
 
C

Christopher Benson-Manica

Mockey Chen said:
struct X{
int x;
char y[0]; /* Note: here array size is ZERO, why? */
};

It's a nonportable hack, at best. It is almost, but not quite, the
"struct hack" that is also nonportable but nevertheless widely used.

http://www.eskimo.com/~scs/C-faq/q2.6.html
Why use array size zero. I heard about the C standard
not allow array with size zero, but my gcc tell me I can
compile this code without error or warning.

You're not invoking it in strictly conforming mode. Use gcc -Wall
-ansi -pedantic and you will see that it does, indeed, warn you that
it is a nonstandard construct.
 
C

Clark S. Cox III

Mockey Chen said:
struct X{
int x;
char y[0]; /* Note: here array size is ZERO, why? */
};

It's a nonportable hack, at best. It is almost, but not quite, the
"struct hack" that is also nonportable but nevertheless widely used.

http://www.eskimo.com/~scs/C-faq/q2.6.html

Though, note that with C99, the following is legal (basically a
legalization of the struct hack):

#include <stdlib.h>

struct X {
int x;
char y[]; //Note empty brackets
};

struct X *allocateX(int count)
{
struct X *result = malloc(count + sizeof *result);
if(result)
{
result->x = count;
}
return result;
}

int main()
{
struct X *x_ptr;

if(x_ptr = allocateX(20))
{
//I can treat x_ptr->y basically as if it were an array of 20 char's
x_ptr->y[19] = 'a';
}

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top