Home > Software design >  structures in c : declaring the new variable in the structure itself
structures in c : declaring the new variable in the structure itself

Time:11-04

Can you explain how we can declare a variable we are currently creatin inside the structure itself please.

typedef struct var var;
struct var {
       int a ;
       var b; };

CodePudding user response:

When you are declaring the variable b within the structure

typedef struct var var;
struct var {
       int a ;
       var b; };

the type struct var is yet an incomplete type. Its size is unknown. So the compiler does not know how much memory to allocate for the data member b and how align data members within teh structure. So you may not declare an object such a way.

From the C Standard (6.7.2.1 Structure and union specifiers)

8 The presence of a struct-declaration-list in a struct-or-union-specifier declares a new type, within a translation unit. The struct-declaration-list is a sequence of declarations for the members of the structure or union. If the struct-declaration-list contains no named members, no anonymous structures, and no anonymous unions, the behavior is undefined. The type is incomplete until immediately after the } that terminates the list, and complete thereafter

But you may use a pointer to an object of the type struct var because pointers are always complete types. For example

typedef struct var var;
struct var {
       int a ;
       var *b; };

CodePudding user response:

In §6.7.2.1 Structure and union specifiers ¶3, the C11 standard says:

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) …

You are attempting to include a member of the same type as the structure you are defining, which is still an incomplete type. That is a 'constraint', which means that a compiler is required to diagnose the problem.

Additionally, the structure you propose would require an infinite amount of storage space, since the structure contains an int and a copy of itself, which contains an int and another copy of itself, which …

  • Related