array of size 0

  • Thread starter Emmanuel Delahaye
  • Start date
E

Emmanuel Delahaye

Hi,

I know that C90 and C9x (N869) doesn't allow to define an array of size 0.

int x[0]; /* constraint violation */

I was under the impression that this was possible in C99, due to the common
C90 practice:

struct a
{
int x;
char y[1];
};

that allows to build a linear structure with an array bigger than one,

struct a
{
int x;
char y[0];
};

char x[123];
struct a *p = (struct a*) x;

or is it just an extension of gcc?

Thanks to clarify my close-to-melt brain.
(we have 40°C in Paris, hopefully, I go to Ireland for holydays next Sunday)
 
K

Kevin Easton

Emmanuel Delahaye said:
Hi,

I know that C90 and C9x (N869) doesn't allow to define an array of size 0.

int x[0]; /* constraint violation */

I was under the impression that this was possible in C99, due to the common
C90 practice:

struct a
{
int x;
char y[1];
};

that allows to build a linear structure with an array bigger than one,

struct a
{
int x;
char y[0];
};

No, the C99 flexible array member looks like:

struct a
{
int x;
char y[];
};
char x[123];
struct a *p = (struct a*) x;

You can't do that, x isn't necessarily correctly aligned for access as
"struct a".

struct a *p = malloc(123);
Thanks to clarify my close-to-melt brain.
(we have 40?C in Paris, hopefully, I go to Ireland for holydays next Sunday)

Bah, we get 40C here every summer :)

- Kevin.
 
D

Dan Pop

In said:
struct a
{
int x;
char y[0];
};

char x[123];
struct a *p = (struct a*) x;

Remember what we keep telling the beginners? Casts are evil in C!
If you don't know what you're doing when casting a pointer, don't do it!
Yeah, all this applies to you, too! If the x array is not properly
aligned for a struct a access, the behaviour of the cast is undefined!
or is it just an extension of gcc?

Why not ask gcc itself?

fangorn:~/tmp 2321> cat test.c
struct a
{
int x;
char y[0];
};
fangorn:~/tmp 2322> gcc -c -std=c99 -pedantic test.c
test.c:4: warning: ISO C forbids zero-size array `y'

To make the struct definition correct for C99, drop the 0 (declare y as a
sizeless array). This is a "flexible array member" in the C99 lingo.

Dan
 
M

Mark A. Odell

With air conditionning, I guess. No such a thing here! Trust me, it's
hell!

Good grief, how can you not have A/C? Do you have running water? :) BTW,
what's the dew point? That's what really makes you uncomfortable.
 

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
474,077
Messages
2,570,566
Members
47,202
Latest member
misc.

Latest Threads

Top