60.5k views
4 votes
Are self-referencing structures legal in ANSI C? (e.g. struct Self_Ref1 { int a; int b; struct Self_Ref1 c; }; )

A) yes
B) no
C) maybe
D) not sure

User Lefloh
by
9.4k points

1 Answer

5 votes

Final answer:

Self-referencing structures in ANSI C are legal when the self-reference is a pointer to the structure type itself. Direct self-reference by containing an instance of the same structure type is not legal, as it would require infinite memory.

Step-by-step explanation:

Self-referencing structures are indeed legal in ANSI C, but with a slight modification to the example provided. In ANSI C, you can have a structure that contains a pointer to the same structure type. However, a structure cannot contain an instance of itself directly as this would create a recursive requirement that would never end, consuming an infinite amount of memory.

The correct way to create a self-referencing structure in ANSI C would look like this:

struct Self_Ref1 {
int a;
int b;
struct Self_Ref1 *c; // self-reference via pointer
};

With this declaration, the 'c' field is a pointer to a structure of the same type, not a structure itself. This allows the compiler to know the size of the structure at compile-time.

The answer to the question is B) no, self-referencing structures are not legal if they contain an instance of themselves directly, but they are legal if they contain a pointer to an instance of the structure.

User Niklas B
by
8.0k points