Structure in C
Structure in C
Structure In
C Language
C Language
Structure In C
We have about various data types in C , imagine a condition where you are asked to create a
heterogeneous data type , means that there is a data type that can hold different kind of data
according to your need.
C provides a user defined data type called "Structure" which allow to hold different kind of data
together.
With the help of structures we can create complex user defined data types.
Suppose there is an university and you are asked to store the data of students like records of
student name, age, department, permanent address etc. So you will require a data type that can
hold these all.
Defining a structure
Syntax :
struct structure_name
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
Here "struct" keyword is used to define structure. The member variable of structure can be of
primary data type or derived data type.
Note : Name of structure is not mandatory but good programming practices suggest to provide
name to the structure.
Structure variables are also optional and you can define them later also.
Semicolon at the end of the structure is mandatory.
Example :
struct StudentDetails
{
char name[25];
2
C Language
int age;
char branch[10];
// F for female and M for male
char gender
char address[50];
};
here name, age, branch, gender and address are called structure element or structure members.
StudentDetail will be of struct type.
struct StudentDetails
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender
char address[50];
} S1, S2;
struct StudentDetails
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender
char address[50];
3
C Language
};
#include<stdio.h>
#include<string.h>
struct Student
{
char name[25];
int age;
char branch[10];
char gender;
};
int main()
{
struct Student s1;
4
C Language
return 0;
Output :
Jay
19
Mathematics
5
C Language
Age of Student : 19
Gender of Student : M
Array Of Structure
We can have array of structure where each element of array will be a structure variable.
#include<stdio.h>
struct Employee
{
char ename[10];
int sal;
};
6
C Language
printf("\nEmployee name is %s", emp[i].ename);
printf("\nSlary is %d", emp[i].sal);
}
}
void main()
{
details();
}
Nesting of Structure
struct student
{
char[30] name;
int age;
//structure for address which has different parts
struct Address
{
char[50] locality;
char[50] city;
int pincode;
}addr;
};
We can pass a structure in a function arguments like we pass any other variable or array.
#include<stdio.h>
struct Student
{
char name[10];
int roll;
};
void main()
7
C Language
{
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
}