user227248
user227248

Reputation: 89

Is the offset of a flexible array member subject to change?

The standard—§6.7.2.1.18—says that

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.

The problem is that i don't understand what the standard means by the last statement. Given that we usually set aside enough memory—using malloc()—for a flexible array member along with that of other members, how can it be possible to have non-successive offsets?

Upvotes: 2

Views: 260

Answers (1)

M.M
M.M

Reputation: 141554

It is saying that if we have:

struct A
{
    int x;
    int a[];
};

struct B
{ 
    int x;
    int b[20];
};

// ...
A *pa = malloc(sizeof(struct A) + sizeof(int[20]));
B *pb = malloc(sizeof(struct B));

then ptr->a behaves exactly like ptr->b except that offsetof(struct B, b) and offsetof(struct A, a), which are both compile-time constants, may be different.

There are some examples in the following paragraphs.

NB. They also behave differently under the action of sizeof so this paragraph seems to be a bit defective.

Upvotes: 1

Related Questions