Sujet : Re: Struct Error
De : bc (at) *nospam* freeuk.com (bart)
Groupes : comp.lang.cDate : 23. Jan 2025, 11:54:10
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vmt74h$1jac0$1@dont-email.me>
References : 1 2
User-Agent : Mozilla Thunderbird
On 23/01/2025 01:05, James Kuyper wrote:
On 2025-01-22, bart <bc@freeuk.com> wrote:
Gcc 14.1 gives me an error compiling this code:
>
struct vector;
struct scenet;
>
struct vector {
double x;
double y;
double z;
};
>
struct scenet {
struct vector center;
double radius;
struct scenet (*child)[];
};
6.7.6.2p2: "The element type shall not be an incomplete or function type."
I have many draft versions of the C standard. n2912.pdf, dated
2022-06-08, says in 6.7.2.1.p3 about struct types that "... the type is
incomplete144) until immediately after the closing brace of the list
defining the content, and complete thereafter."
Therefore, struct scenet is not a complete type until the closing brace
of it's declaration.
Wouldn't this also be the case here:
struct scenet *child;
};
The struct is incomplete, but it still knows how to do pointer arithmetic with that member. The calculation is not that different from the array version (actually, the code from my compiler is identical).
However, that sentence disappeared in n3047.pdf, dated 2022-08-04. Can
anyone tell me why it was removed? With it gone, I'm not sure it is
still considered an incomplete type.
Ignoring for the moment the fact that it's not permitted, why do you
want to do that? In C code, people usually use pointers to the first
element of an array rather than pointers to arrays. However, it
sometimes is a good idea to have a pointer to an array, because that
makes the length of the array part of the pointer type, which can be
used to check the validity of the code that uses that pointer to access
the elements of the array. But in this case, the length of the array is
unspecified, so there's no such benefit.
I said the code is generated, which means the original language uses a pointer-to-array at that spot.
That is safer, as you can't mistakenly index a pointer which happens to be a reference to a single instance.
In any case, you should surely be able to choose a T(*)[] type over T* if you want, but apparently not inside a self-referential struct.