0

I have noticed that an empty array in the end of the structure is often used in open source projects:

typedef struct A
{
    ......
    void *arr[];
} A;  

I want to know is this a C standard? Or only OK for gcc compiler?

Nan Xiao
  • 16,671
  • 18
  • 103
  • 164

2 Answers2

4

As of C99, it is now a C standard. Pre-C99 compilers may not support it. The old approach was to declare a 1-element array, and to adjust the allocation size for that.

New way:

typedef struct A
{
    ......
    void *arr[];
} A;  

int slots = 3;
A* myA = malloc(sizeof(A) + slots*sizeof(void*));
myA->arr[2] = foo;

Old way:

typedef struct A
{
    ......
    void *arr[1];
} A;  

int slots = 3;
A* myA = malloc(sizeof(A) + (slots-1)*sizeof(void*));
myA->arr[2] = foo;
Sneftel
  • 40,271
  • 12
  • 71
  • 104
  • 1
    Is the following case possible? That is for data aligned, there are padding bytes in the end of struct A. so there is a gap between myA->arr[0] and myA->arr[1]. – Nan Xiao Mar 06 '14 at 09:45
  • 1
    Padding can lead to allocating more memory than is actually needed, but it won't cause problems with the calculation of array slot addresses. If `sizeof(void*)==4`, then `arr[1]` will be four bytes after `arr[0]`, no matter how `A` is padded. – Sneftel Mar 06 '14 at 10:15
  • Nice catch, though. You're right, padding makes this technique a little weird. – Sneftel Mar 06 '14 at 10:16
1

The standard (draft N1570) 18 of 6.7.2.1, states:

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply. However, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.

Sadique
  • 22,572
  • 7
  • 65
  • 91
  • 2
    Quoting the standard is good, but an explanation of why someone would do this and how it's used in practice would be nice. – Jon Mar 06 '14 at 09:36