Search⌘ K

Structure and Pointers

Explore the use of structure pointers in C programming, including how to access members using the arrow operator. Understand pointers to arrays of structures, their memory implications, and common errors. This lesson helps you handle complex data structures effectively using pointers.

What is a structure pointer?


A pointer pointing to a struct is known as a structure pointer.


Example program

The program given below demonstrates the use of a structure pointer.

C
# include <stdio.h>
int main( )
{
// Declare structure book
struct book
{
char n[ 20 ] ;
int nop ;
float pr ;
} ;
// Initialize structure variable
struct book b = { "Basic", 425, 135.00 } ;
// Declare pointer to structure variable
struct book *ptr;
// Store address of structure variable
ptr = &b;
// Access structure elements using dot operator
printf ( "%s %d %f\n", b.n, b.nop, b.pr ) ;
// Access structure elements using arrow operator
printf ( "%s %d %f\n", ptr->n, ptr->nop, ptr->pr ) ;
}

Explanation

In the code given above, ptr is a pointer to a structure, not a structure variable. Therefore, we cannot use ...