Introduction to Structures in C: A Beginner’s Guide

The structure is a user-defined data type. It can be a collection of elements that belong to different data types. The structure reduces the pitfalls of the array that is array is a collection of similar data types.

How to use Structures?

For using structure in our program we need to take the following steps.

  1. At first we define the structure or declare the structure.
  2. Then we declare structure variable.
  3. After the declaration of structure variable we access structure elements.

Now we will see how we take the above three steps one by one which is written in bold.

Defining or Declaring a structure:

The format of defining a structure is given below where at first we write struct keyword that is followed by structure_name, then in the body of the structure, we write its element. Syntax or format:

struct structure_name
{
	Data type element 1;
 	Data type element 2;
	Data type element 3;
	Data type element n;
};

For example, suppose we have to define a structure that will contain the name and age of the student. To define it we write the following statements:

struct Student
{
	char name[20];
	int Age;
}; 

Declaring Structure Variables:

Declaration of Structure Variables is like basic data types try to understand the concept, for the declaration of integral variable you write int keyword which is followed by the variable name. The same approach is here for the declaration of structure variable at first you write structure name then you write structure variable name. Syntax or format:

Struct structure_name variable_name1, variable_name2, ...........n;

For the above structure if we have to declare a structure variable then we need to write the following statement:

struct Student s1,s2; // this statement will reserve space for two
                      //structure one for s1 and another for s2.

Accessing structure elements:

Structure elements are accessed by structure variable followed by dot(.) operator. Format or Syntax:

Structure variablename.element_name;

For example, suppose we have to access the name and age of structured student then to access this we will write:

s1.name
s1.age 
s2.name
s2.age

Array of Structures

An array of structures is a collection of similar structures.

For example: To store data of books, we would be required to use 10 different structure variables from b1 to b10, which is definitely not very convenient. A better approach would be to use an array of structures.

The below program shows how to use an array of structures:

// usage of an array of structure
#include <stdio.h>
void linkfloat();
int main()
{
    struct book
    {
        char name;
        floar price;
        int pages;
    };
    
    struct book b[10];
    
    for(int i = 0; i<=9; i++)
    {
         printf("Enter name, price and pages:");
         fflush(stdin);
         scanf("%c%f%d",&b[i].name, &b[i].price, &b[i].pages);
    }

    printf("Name\tPrice\tPages\n");
   
    for(int i = 0; i<=9; i++)
    {
         printf("%c\t%f\t%d\n",b[i].name, b[i].price, b[i].pages);
    }

    return 0;
}

void linkfloat()
{
     float a = 0, *b;
     b = &a; // cause emulator to be linked
     a = *b; // suppress the warning - variable not used
}

The Input for the program is…

Enter name, price and pages:a 120 12 
Enter name, price and pages:b 130 13
Enter name, price and pages:c 140 14 
Enter name, price and pages:d 150 15
Enter name, price and pages:e 160 16
Enter name, price and pages:f 170 17
Enter name, price and pages:g 180 18
Enter name, price and pages:h 190 19
Enter name, price and pages:i 200 20
Enter name, price and pages:j 210 21

The output (result) of the program…

Name      Price        Pages
a       120.000000      12
b       130.000000      13
c       140.000000      14
d       150.000000      15
e       160.000000      16
f       170.000000      17
g       180.000000      18
h       190.000000      19
i       200.000000      20
j       210.000000      21

Additional Features of Structures

There are the following features of structures.

(a) The values of a structure variable can be assigned to another structure variable of the same type using the assignment operator. This is shown in the following example.

main( ) 
{ 
struct employee 
{ 
char name[10] ; 
int age ; 
float salary ; 
} ; 
struct employee e1 = { "Sanjay", 30, 5500.50 } ; 
struct employee e2, e3 ; 
/* piece-meal copying */ 
strcpy ( e2.name, e1.name ) ; 
e2.age = e1.age ; 
       e2.salary = e1.salary ; 
/* copying all elements at one go */ 
e3 = e2 ; 
printf ( "\n%s %d %f", e1.name, e1.age, e1.salary ) ; 
printf ( "\n%s %d %f", e2.name, e2.age, e2.salary ) ; 
printf ( "\n%s %d %f", e3.name, e3.age, e3.salary ) ; 
} 

The output of the program would be…

Sanjay 30 5500.500000 
Sanjay 30 5500.500000 
Sanjay 30 5500.500000 

(b) One structure can be nested within another structure. Using this facility complex data types can be created. The following program shows nested structures at work.

main( ) 
{ 
struct address 
       { 
char phone[15] ; 
char city[25] ; 
int pin ; 
} ; 
struct emp 
{ 
char name[25] ; 
struct address a ; 
} ; 
struct emp e = { "jeru", "531046", "nagpur", 10 }; 
printf ( "\nname = %s phone = %s", e.name, e.a.phone ) ; 
printf ( "\ncity = %s pin = %d", e.a.city, e.a.pin ) ; 
} 

The output would be…

And here is the output... 
name = jeru phone = 531046 
city = nagpur pin = 10 

(c) Like an ordinary variable, a structure variable can also be passed to a function. We may either pass individual structure elements or the entire structure variables at one go.

main( ) 
{ 
struct book 
{ 
char name[25] ; 
char author[25] ; 
int callno ; 
} ; 
struct book b1 = { "Let us C", "YPK", 101 } ; 
display ( b1.name, b1.author, b1.callno ) ; 
} 

display ( char *s, char *t, int n ) 
{ 
printf ( "\n%s %s %d", s, t, n ) ; 
} 

And here is the output…

Let us C YPK 101 

(d) The way we can have a pointer pointing to an int, or a pointer pointing to a char, similarly, we can have a pointer pointing to a struct. Such pointers are known as ‘structure pointers’.

main( ) 
{ 
struct book 
{ 
char name[25] ; 
char author[25] ; 
int callno ; 
} ; 
struct book b1 = { "Let us C", "YPK", 101 } ; 
struct book *ptr ; 
ptr = &b1 ; 
printf ( "\n%s %s %d", b1.name, b1.author, b1.callno ) ; 
printf ( "\n%s %s %d", ptr->name, ptr->author, ptr->callno ) ; 
} 

The first printf( ) is as usual. The second printf( ) however is peculiar. We can’t use ptr.name or ptr.callno because ptr is not a structure variable but a pointer to a structure, and the dot operator requires a structure variable on its left. In such cases, C provides an operator ->, called an arrow operator to refer to the structure elements. Remember that on the left-hand side of the ‘.’ structure operator, there must always be a structure variable, whereas on the left-hand side of the ‘->’ operator there must always be a pointer to a structure.

Passing an entire array of structure to a function:

Suppose we have to pass the above array of structure to a function  by reference, for this we need to pass the base address of the structure’s array to the function by the following function call:

INPUT(&s[0]);  \\ This statement will call the definition and  pass the 
                \\base address(1010) to the function definition.  

INPUT(struct student *P) \\ Here P will hold the base address 
{
	[we can access memory locations using (P+i) ->Name, (P+i) ->Age]
}

Uses of Structures

The immediate application that comes to mind is Database Management. That is, to maintain data about employees in an organization, books in the library, items in a store, etc.

You can also use structures much beyond database management. They can be used for a variety of purposes like:

  • Changing the size of the cursor.
  • Clearing the content of the screen.
  • Placing the cursor at an approprate position on screen.
  • Drawing any graphics shape on the screen.
  • Receiving a key from the keyboard.
  • Checking the moemory size of the computer.
  • Finding out the list of equipment attached to the computer.
  • Formating a floppy.
  • Hinding a file from the directory.
  • Displaying the directory of a disk.
  • Sending the output to printer.
  • Interacting with the mouse.