Declaration of Structures:
Method 1:
A structure is a user defined data structure in c language. To declare a structure you must start with the keyword struct followed by the structure name or structure tag and within curly braces the list of the structure’s member variables. It does not create any variables or instances. The syntax of structure declaration is as follows.
struct structure-tag{
Data type variable1
Data type variable2
Data type variable3
};
For example consider the student data base in which each student has a student id (stid) number name, course, address and the marks. These elements together form as a structure with name cstudent we can have the declaration of structure as below;
struct cstudent {
int stid;
char name [20];
char course[20];
char address[20];
int marks obtained;
};
In the above method no memory is allocated for the structure. This is only the definition of structure that tells us that there exists a user defined data type by the name of student which is composed of the following members .Using this structure type we have to create the variables/instances for the structure
struct student cst1;
Here cst1 is the variable for the structure. When we call cst1, the total structure is available. Now memory will be allocated. The amount of memory allocated will be the sum of all the data members which form part of the structure template.
Below is the demo program for the structure:
#include<stdio.h>
#include<conio.h>
struct cstudent{
int stid;
char name[20];
char course[20];
char address[20];
int marks;
};
main(){
cstudent cs1;
printf(“Enter below details of the student:”);
printf(“\n Enter the student id”);
scanf(“%d”,&cs1.stid);
printf(“\n Enter name of student”);
scanf(“%s”,&cs1.name);
printf(“\n Entername of the Course “);
scanf(“%s”,&cs1.course);
printf(“\n Enter address of the student “);
scanf(“%s”,&cs1.address);
printf(“\n Enter marks of the student”);
scanf(“%d”,&cs1.marks);
printf(“\n You entered details below”);
printf(“\n Student ID”,cs1.stid);
printf(“\n Student Name”,cs1.name);
printf(“\n Student Address”, cs1.address);
printf(“\n Student Course”,cs1.course);
printf(“\n Student Marks”,cs1.marks);
getch();
}
To compile the above program Press : Alt + f9.
Run the program press Ctrl+f9
To see the output : Alt+f5.
Here no need to use Alt+F5 because we used getch() function to see the immediate output.
Output as follows:
Enter below details of the student:
Enter the student id : 1004
Enter name of student : Suseel
Enter name of the Course : PGDCA
Enter address of the student : Vizag
Enter marks of the student : 98
You entered details below
Student ID 1004
Student Name Suseel
Student Address Vizag
Student Course PGDCA
Student Marks 98