C : Programming Language

Structure

A structure in C, is a simple user defined data structure which groups dissimilar kind of data in close memory location.

For example, we want to store information of a student like his/her name, roll number and class then we could do it easily by creating three separate variables like name, roll_number and class but imagine if we need to store information for 100 students then the number of variables would be 300 and then managine these many variables would be cumbersome. So structures in C, helps us to group such information using a user defined structured data type.

Example:

#include <stdio.h>
int main() {
struct student {
char *name;
int roll_number;
int class;
};

//store values in stucture 's'
struct student s = {"Pawan", 17, 9};

//print values stored in structure 's'
printf("Name = %s\nRoll Number = %d\nClass = %d", s.name, s.roll_number, s.class);
}

Output:

Name = Pawan
Roll Number = 17
Class = 9

Example:

#include <stdio.h>
int main() {
struct student {
char *name;
int roll_number;
int class;
};

//declare stucture 's'
struct student s;

//store values in stucture 's'
s.name = "Pawan";
s.roll_number = 17;
s.class 9};

//print values stored in structure 's'
printf("Name = %s\nRoll Number = %d\nClass = %d", s.name, s.roll_number, s.class);
}

Output:

Name = Pawan
Roll Number = 17
Class = 9