Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Nested structures

Node:Nested structures, Next:, Previous:Arrays of structures, Up:struct



Nested structures

Structures can contain other structures as members; in other words, structures can nest. Consider the following two structure types:

struct first_structure_type
{
  int integer_member;
  float float_member;
};

struct second_structure_type
{
  double double_member;
  struct first_structure_type struct_member;
};

The first structure type is incorporated as a member of the second structure type. You can initialize a variable of the second type as follows:

struct second_structure_type demo;

demo.double_member = 12345.6789;
demo.struct_member.integer_member = 5;
demo.struct_member.float_member = 1023.17;

The member operator . is used to access members of structures that are themselves members of a larger structure. No parentheses are needed to force a special order of evaluation; a member operator expression is simply evaluated from left to right.

In principle, structures can be nested indefinitely. Statements such as the following are syntactically acceptable, but bad style. (See Style.)

my_structure.member1.member2.member3.member4 = 5;

What happens if a structure contains an instance of its own type, however? For example:

struct regression
{
  int int_member;
  struct regression self_member;
};

In order to compile a statement of this type, your computer would theoretically need an infinite amount of memory. In practice, however, you will simply receive an error message along the following lines:

struct5.c: In function `main':
struct5.c:8: field `self_member' has incomplete type

The compiler is telling you that self_member has been declared before its data type, regression has been fully declared -- naturally, since you're declaring self_member in the middle of declaring its own data type!

 
 
  Published under free license. Design by Interspire