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 - Pointers to structures

Node:Pointers to structures, Next:, Previous:Nested structures, Up:struct



Pointers to structures

Although a structure cannot contain an instance of its own type, it can can contain a pointer to another structure of its own type, or even to itself. This is because a pointer to a structure is not itself a structure, but merely a variable that holds the address of a structure. Pointers to structures are quite invaluable, in fact, for building data structures such as linked lists and trees. (See Complex data structures.)

A pointer to a structure type variable is declared by a statement such as the following:

struct personal_data *my_struct_ptr;

The variable my_struct_ptr is a pointer to a variable of type struct personal_data. This pointer can be assigned to any other pointer of the same type, and can be used to access the members of its structure. According to the rules we have outlined so far, this would have to be done like so:

struct personal_data person1;

my_struct_ptr = &person1;
(*my_struct_ptr).day_of_birth = 23;

This code example says, in effect, "Let the member day_of_birth of the structure pointed to by my_struct_ptr take the value 23." Notice the use of parentheses to avoid confusion about the precedence of the * and . operators.

There is a better way to write the above code, however, using a new operator: ->. This is an arrow made out of a minus sign and a greater than symbol, and it is used as follows:

my_struct_ptr->day_of_birth = 23;

The -> enables you to access the members of a structure directly via its pointer. This statement means the same as the last line of the previous code example, but is considerably clearer. The -> operator will come in very handy when manipulating complex data structures. (See Complex data structures.)

 
 
  Published under free license. Design by Interspire