struct [structure_name]
{
//data_type var 1
//data_type var 2
//data_type var 3 ..
}
[structure_variables];
Defining a structure to store students ID, marks and favourite character
struct Student
{
int id;
int marks;
char fav_char;
} s1,s2,s3;
// new datatype whose name is student and this is achieved by structure;
We can either declare a structure along with structure definition or separately.
//Declaring a structure along with structure definition
#include <stdio.h>
struct Employee
{
int id;
char name[53];
float marks;
};
struct Employee e1,e2;
int main()
{
return 0;
}
//Declaring a structure separate from structure definition
#include <stdio.h>
struct Employee
{
int id;
char name[53];
float marks;
} e1,e2;
int main()
{
struct Employee tt;
//this creates one more variables
return 0;
}
We can either initialize a structure along with structure definition or separately.
//Initializing a structure along with structure definition
#include <stdio.h>
struct Employee
{
int id;
float marks;
};
struct Employee e1,e2;
int main()
{
struct Employee e1;
e1.id = 12;
e1.marks = 34.12;
return 0;
}
//Initializing a structure separate from structure definition
#include <stdio.h>
struct Employee
{
int id;
float marks;
};
int main()
{
struct Employee e1 = {12, 34.12};
return 0;
}
#include <stdio.h>
#include <string.h>
struct Student
{
int id;
int marks;
char fav_char;
char name[34];
};
int main()
{
struct Student harry, ravi;
harry.id = 1;
harry.marks = 466;
strcpy(harry.name, "Harry Coder");
harry.fav_char = 'p';
ravi.id = 2;
ravi.marks = 466;
ravi.fav_char = 'p';
strcpy(ravi.name, "Ravi Kumar");
struct Student subham = {3, 466, 'p', "Subham Kumar"};
// printf("Harry got %d marks", harry.marks);
// quick quiz
// print all information of a given student
printf("Harry's full name is %s, ID is %d, marks = %d and favourite character = %c \n", harry.name, harry.id, harry.marks, harry.fav_char);
printf("Ravi's full name is %s, ID is %d, marks = %d and favourite character = %c\n", ravi.name,
ravi.id, ravi.marks, ravi.fav_char);
printf("Subham's full name is %s, ID is %d, marks = %d and favourite character = %c\n", subham.name, subham.id, subham.marks, subham.fav_char);
return 0;
}