In C programming struct is a structured (record type) that creates a collection of different type of variable under a single name. If we want to store record of student. We can store name , rollno, phone no , address etc. using one variable, then struct makes it possible.
Syntax of struct in c :
struct tag_name {
type attribute;
type attribute;
/ * ……. */
};
For example to store info of student :
1 2 3 4 5 6 |
struct stu_info { int rollno; char name[50]; char city[10]; char mobile[12]; }; |
Declaration of stu_info :
1 |
struct stu_info s1; |
Accessing attributes:
Accessing attribute rollno;
rollno can be accessed by s1.rollno;
similiary other varibles also can be accessed.
Pointer to the struct:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include<stdio.h> struct stu_info { int rollno; char name[50]; char city[10]; char mobile[12]; }; int main(){ struct stu_info s1; struct stu_info *p1; p1=&s1; //To access attribute by pointer we must use -> instead of . scanf("%d",&(p1->rollno)); scanf("%s",p1->name); scanf("%s",p1->city); scanf("%s",p1->mobile); printf("n Student info :"); printf("nRollno : %d",p1->rollno); printf("nName : %s",p1->name); printf("nCity : %s",p1->city); printf("nMobile : %s",p1->mobile); return 0; } |
Array of structure :
We have seen array of int , float , char .Similarly array of struct can also be defined. This is used to store students info , customer info etc..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#include<stdio.h> struct stu_info { int rollno; char name[50]; char city[10]; char mobile[12]; }; int main(){ struct stu_info student[100]; //declaration of stu_info array of size 100 int i,n; printf("Enter the Class streangth < 100 : "); scanf("%d",&n); // for loop for feeding data from stdin for(i=0;i<n;i++){ printf("Enter the %d student info :",i+1); student[i].rollno=i+1; printf("nName :"); scanf("%s",student[i].name); printf("City :"); scanf("%s",student[i].city); printf("Mobile :"); scanf("%s",student[i].mobile); } // for loop for printing student info for(i=0;i<n;i++){ printf("nnStudent %d info :",i+1); printf("nRollno : %d",student[i].rollno); printf("nName : %s",student[i].name); printf("nCity : %s",student[i].city); printf("nMobile : %s",student[i].mobile); } return 0; } |