Darrell Darrell - 2 months ago 18
C Question

Variations of struct definitions in C

I have built a struct in two ways, see below (Fig. A & Fig. B). In my .c file I access the struct like so (Fig. C).

Can someone please explain why Figure A makes a compiler error when accessed by Fig. C. Also, why Figure B doesn't cause a compiler error when accessed using Fig. C? Fig.

I can appreciate the syntax, if the struct is being used inside itself, the name needs to be in two places, top and bottom of struct.

Is it related to a 'forward reference' of sorts for the compiler? A good explanation would be appreciated.

//Fig. A
typedef struct
{
uint32_t* block_address;
struct mem_table_entry_t* next_entry_ptr;

}mem_table_entry_t;

typedef struct
{
mem_table_entry_t two_kib[8];

}mem_table_t;


and

//Fig. B
typedef struct mem_table_entry_t;
{
uint32_t* block_address;
struct mem_table_entry_t* next_entry_ptr;

}mem_table_entry_t;

typedef struct
{
mem_table_entry_t two_kib[8];

}mem_table_t;


...

//Fig. C
memory_table.two_kib[block].next_entry_ptr = &memory_table.two_kib[block+1];

Answer

In snippet A, there is no struct mem_table_entry_t defined [yet] in the struct tag namespace. So you cannot refer to it as in struct mem_table_entry_t* next_entry_ptr;.

Your snippet B is correct.

Note also that the typedef namespace is distinct from the struct tag namespace. This means the the following are not compatible:

mem_table_entry_t two_kib1[8];
struct mem_table_entry_t two_kib2[8];
Comments