Structure in C

In this section of the C programming tutorial, you will learn about structures and unions. We will first have a look at structures.

What is structure in the C programming language?

Structure(defined as struct) in C programming language is a complex data type that defines a physically grouped list of variables under one name in a memory block that allows you to access different variables with a single pointer or by the declared name structure that returns the same address.

  • If you want to access members of a structure in C, you must change the structure variable.
  • Many structure variables can be declared for one structure, and memory will be allocated for each.
  • Structure data type may contain other types of data, so it is used for records of mixed data types, such as recording a directory on the hard disk.

Declaration of structure in C 

The general syntax for a struct declaration in C is:

struct tag_name {
   type member1;
   type member2;
   ... 
   type member;
};

Defining a Structure

The general syntax for a defining a struct in C is:

struct [structure tag] {
   member1 definition;
   member2 definition;
   ...
   member definition;
} [one or more structure variables];
Using normal variable Using pointer variable
Syntax:
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Syntax:
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example:
struct student
{
int  mark;
char name[10];
float average;
};
Example:
struct student
{
int  mark;
char name[10];
float average;
};
Declaring structure using normal variable:
struct student report;
Declaring structure using pointer variable:
struct student *report, rep;
Initializing structure using normal variable:
struct student report = {100, “Mani”, 99.5};
Initializing structure using pointer variable:
struct student rep = {100, “Mani”, 99.5};
report = &rep;
Accessing structure members using normal variable:
report.mark;
report.name;
report.average;
Accessing structure members using pointer variable:
report  -> mark;
report -> name;
report -> average;

Example of structure in C programming language:

The following example shows how to use a structure in a program.

#include <stdio.h>
#include <string.h>
struct student
{
int rollno;
char name[60];
}s1;  //declaring s1 variable for structure
void main( )
{
s1.rollno=234;
strcpy(s1.name, “John”);//copying string into char array
//printing first employee information
printf( "Rollno : %d\n", s1.rollno);
printf( "Name : %s\n", s1.name);
}

Output:

Rollno : 234
Name : John

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping cart