Structure
Structure
Structure Declaration
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;
Example
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
2. Structure Variable Declaration after Structure
Example
Let's see the example to declare the structure variable by
struct keyword. It should be declared within the main function.
struct employee
{ int id;
char name[50];
float salary;
};
struct myStructure {
int myNum;
char myLetter;
};
int main() {
struct myStructure s1;
return 0;
}
E.g.
struct employee
{ int id;
char name[10];
float salary;
};
Memory allocation:
Access Structure Members:
Syntax
structure_name.member1;
strcuture_name.member2;
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
So, we initialize
EXAMPLE:
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal"); //copying string into char array
e1.salary=56000;
//store second employee information
e2.id=102;
strcpy(e2.name, "James Bond");
e2.salary=126000;
//printing first employee information Output:
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name); employee 1 id : 101
printf( "employee 1 salary : %f\n", e1.salary); employee 1 name : Sonoo Jaiswal
//printing second employee information employee 1 salary : 56000.000000
printf( "employee 2 id : %d\n", e2.id); employee 2 id : 102
printf( "employee 2 name : %s\n", e2.name); employee 2 name : James Bond
employee 2 salary :
printf( "employee 2 salary : %f\n", e2.salary);
126000.000000
return 0;
}
Array of Structures
#include<stdio.h>
struct student
{
char name[20];
int id;
float marks;
};
void main()
{
struct student s1,s2,s3;
int dummy;
printf("Enter the name, id, and marks of student 1 ");
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 2 ");
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 3 ");
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
scanf("%c",&dummy);
printf("Printing the details....\n");
printf("%s %d %f\n",s1.name,s1.id,s1.marks);
printf("%s %d %f\n",s2.name,s2.id,s2.marks);
printf("%s %d %f\n",s3.name,s3.id,s3.marks);
}
Output
Enter the name, id, and marks of student 1 James 90 90
Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90