Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible for a C struct to reference itself?

Tags:

c

gcc

How does a C compiler (I'm using GCC) know what to do with the following?

struct node
{
    int x;
    struct node* next;
};

More precisely, if node has yet to be completely defined yet (we have not reached the closing curly brace), then how does the compiler know how big a struct ought to be?

While I realize that "pointing to" only requires an address, incrementing pointers does require the size of the data it points to.

like image 408
robert.ecot Avatar asked Sep 04 '13 13:09

robert.ecot


People also ask

Can a struct reference itself?

Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member. In other words, structures pointing to the same type of structures are self-referential in nature.

Are self-referential structures are possible in C?

The self-referential structure is a structure that points to the same type of structure. It contains one or more pointers that ultimately point to the same structure. Structures are a user-defined data structure type in C and C++.

What do you mean by self-referential structures?

A self-referential structure is a structure that can have members which point to a structure variable of the same type. They can have one or more pointers pointing to the same type of structure as their member.

What is self in C?

In many object-oriented programming languages, this (also called self or Me ) is a variable that is used in instance methods to refer to the object on which they are working. The first OO language, SIMULA 67, used this to explicitly reference the local object.


1 Answers

The size of the struct is not important, as a pointer to the struct is being stored, not the struct itself.

In terms of incrementing pointers to struct; that is done outside of the struct definition, so again, is not important.

like image 150
trojanfoe Avatar answered Oct 27 '22 00:10

trojanfoe