Inflexible array members

A

Adam Warner

Hi all,

One cannot return a pointer to an array in C since there are no first
class array types. But one can return a pointer to an incomplete array via
the illegal but widely supported zero array struct hack:

#include <stdlib.h>

typedef struct byte_vector_t byte_vector_t;

struct byte_vector_t {
unsigned char byte[0];
};

int main() {
byte_vector_t *byte_vector=malloc(10);
byte_vector->byte[9]=42;
return 0;
}

It is frequently stated that flexible array members are a substitute for
the zero array struct hack. Let's see (by compiling file array.c below
with GNU C):

#include <stdlib.h>

typedef struct byte_vector_t byte_vector_t;

struct byte_vector_t {
unsigned char byte[];
};

int main() {
byte_vector_t *byte_vector=malloc(10);
byte_vector->byte[9]=42;
return 0;
}

$ gcc -std=c99 array.c
array.c:6: error: flexible array member in otherwise empty struct

GCC refuses to compile this code because C99 states (6.7.2.1,
paragraph 2):

A structure or union shall not contain a member with incomplete or
function type (hence, a structure shall not contain an instance of
itself, but may contain a pointer to an instance of itself), except
that the last member of a structure with more than one named member may
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
have incomplete array type; such a structure (and any union containing,
possibly recursively, a member that is such a structure) shall not be a
member of a structure or an element of an array.

This restriction is repeated in paragraph 16.

The struct types are intended to serve as self-documenting code and stop
me from incorrectly indexing a pointer to a single value (and vice versa).
Typedefs also lead to self-documenting code but provide no additional
compile-time type safety.

Is this restriction upon flexible array members sensible? The core syntax
and semantics are better because one should not index past the elements of
an array (and a zero sized array has no elements). Is there a standard way
I can maintain the extra type safety of structs with an incomplete array
member without having to pad those struts with a non-zero sized header?

Many thanks,
Adam
 

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,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top