Structure in C Programming Language With Example

Structure in C Programming Language With Example

In C Programming Language Structure is a very useful and most used concept and data type. Actually we all know that C Programming Language has no sign of Classes and Objects. So to fulfil that similar lack, C has the concept of Structure.

Basically, the structure is a group of variables of different data types represented by a single name.

Lets know before move on the program that

Why structure is useful with the real world example?

Suppose In a class there are many students and we know that every student have their some own property like name, Age, roll number etc.

Now If we want to store the information of one students like his name, age and roll number so we can easily store its information in three variables. And if we need to store the information of two students then we need some more variable. So for 2 or 3 students it is possible but the problem will arise if we have to store the information of whole students of the class. It is very difficult to store the information of all students in variable alone.

So to solve that problem C have a concept of structure. Below is a syntax of C Structure.

Syntax of Structure

[c]
struct Student{
char *name;
int age;
int roll;
};
struct Student std1, std2;
[/c]

Explanation of Structure

We should use the struct keyword, and after that give the name of the structure. Then in the body part of the structure, we declare different data types.
In the Above Example, we have char, and int data type in the one structure.
After the body of the structure, we declare the name of the variable belongs to the Student structure.

Example of Structure in C Language

[c] #include<stdio.h> #include<conio.h> struct Student{ char *name; int age; int roll; }; int main() { struct Student std; std.name = "Prakash"; std.age = 20; std.roll = 2; printf("Name of student is: %s", std.name); printf("\nAge of student is: %d", std.age); printf("\nRoll no of student is : %d", std.roll); getch(); } [/c]

Output

Structure Example in C