Structures in C Programming Language

Notes:

Structures in C programming language:
- Structure is a collection of logically related different type of data elements.
- Structure is a collection of logically related heterogeneous data elements.

- While solving any real world problem using C programming language; we may need to represent different real world entities inside a C program. To represent any real world entity in a C program, we take help of structures.

Ex:
College Management System Application – Student, Faculty, Subject etc.
Mathematical Application – Point, Rectangle, Circle etc.

Note:
- Structures are also used to create data structures like linked lists, stacks, queues, graphs, trees etc.

Syntax for defining a structure: a template or blue print for any real world entity

// defining a structure
struct StructureName
{
data_type variableName1;
data_type variableName2;

data_type variableNameN;
};

EX: // defining a Student structure
struct Student
{
int rollnum;
char *name;
float marks;
};

Syntax for declaring a structure variable:
- There are two different ways in which we can declare a structure variable or instance of a structure

// declaring a structure variable while defining a structure
struct StructureName
{
data_type variableName1;
data_type variableName2;

data_type variableNameN;
} list of structureVariableNames separated by comma;

EX:
struct Student
{
int rollnum;
char *name;
float marks;
} student1, student2;

OR

// declaring a structure variable after defining a structure
struct StructureName structureVariableName;

EX:
struct Student student1;
struct Student student2;

Syntax for declaring and initializing a structure variable:
- There are two different ways in which we can declare and initialize a structure variable

// declaring and initializing a structure variable while defining a structure
struct StructureName
{
data_type variableName1;
data_type variableName2;

data_type variableNameN;
}

structureVariableName1 = {set of values separated by comma},
structureVariableName2 = {set of values separated by comma},

structureVariableNamen = {set of values separated by comma};

EX:
struct Student
{
int rollnum;
char *name;
float marks;
}

student1= {1, “Suresh”, 76.5},
student2= {2, “Ramesh”, 86.5};

OR

// declaring and initializing structure variable after defining a structure
struct StructureName structureVariableName = {set of values separated by comma};

EX:
struct Student student1 = {1, “Suresh”, 76.5};
struct Student student2 = {2, “Ramesh”, 86.5};

Syntax for getting members of a structure variable using Dot operator:

// getting member of a structure variable
structureVariableName.membername

EX:
printf(“%f\n”,student1.marks); // 76.5

Syntax for setting members of a structure variable using Dot operator:

// setting member of a structure variable
structureVariableName.membername = value;

EX:
student1.marks = 86.5;