Structure in c programming

 

Introduction

Ø  Structure in C is a user-defined data type.

Ø  It is used to bind two or more similar or different data types or data structures together into a single type.

Ø  The structure is created using the struct keyword, and a structure variable is created using the struct keyword and the structure tag name.

Ø  A data type created using structure in C can be treated as other primitive data types of C to define a pointer for structure, pass structure as a function argument or a function can have structure as a return type.

Why Use Structure?

Ø  Imagine we have to store some properties related to a Student like a Name, Class, and Section.

Ø  We have one method to create a character array to store the Name, integer variable for Class, and character variable for Section.

Ø  Storing data for a single student is easy, but imagine creating that many variables for 50 students or even 500 or more.

Ø  So to handle this type of problem, we need to create a user-defined data type that can store or bind different types of data types together, this can be done with the help of structure in C.

Structure  syntax

            Syntax:

            struct structure_name

            {

                Data_member_type data_member_defination;

                Data_member_type data_member_defination;

                Data_member_type data_member_defination;

                ...

                ...

            }(structure_variables);

            Example:

            struct Student

            {

                char name[50];

                int class;

                int roll_no;

            } student1;

Declaration

Ø  There are two ways to declare variables for structure in C language:

Ø  First Way:

struct structure_name {

    // body of structure

} variables;

struct Student {

    char name[50];

    int class;

    int roll_no;

} student1; // here 'student1' is a structure variable of type, Student.

Ø  In the above example, Student structure is created and the student1 variable is declared for it just after the structure definition.

            Second Way:

Ø  As we create a structure in C, we have created a user-defined data type. So this data type can be treated as the primitive data type while declaring a variable for that structure.

struct Student

{

    char name[50];

    int class;

    int roll_no;

};

int main()

{

    //struct structure_name variable_name;

    struct Student a; // here a is the variable of type Student

    return 0;

}

Initialization

Ø  Initializing a structure member means assigning values to the structure members according to their respective data types.

Ø  But declaration doesn't allocate memory for the structure.

Ø  When we declare a variable for a structure, only then is the memory allocated to that structure variable.

Ø  Hence, assigning value to something that doesn't have memory is the same as serving food without a plate, which isn't a good idea!

Ø  In short, structure members cannot be initialized during the declaration.

Ø  For example:

struct Student

{

    char name[50] = {"Student1"};  

 // COMPILER ERROR:  cannot initialize members here

    int class = 1;                  

// COMPILER ERROR:  cannot initialize members here

    int roll_no = 5;               

 // COMPILER ERROR:  cannot initialize members here

};

Ø  There are three ways to initialize structure members:

Ø  Using dot '.' operator

Ø  Using curly braces ‘{}’

Ø  Designated initializers

Using dot '.' operator

Ø  Using the dot (.) operator, we can access any structure member and then initialize or assign its value according to its data type.

Ø  Syntax:

Ø  struct structure_name variable_name;

Ø  variable_name.member = value;

Ø  In the above syntax first, we created a structure variable, then with the help of the dot operator accessed its member to initialize them.

Example

            #include <stdio.h>

            #include <string.h>

            struct Student {

             char name[50];

             int class;

             char section;

            };

            int main() {

              struct Student student1;

             strcpy(student1.name,“Rakesh");

             student1.class = 1;

             student1.section = 'A';

            // printing values

             printf( "Student Name : %s\n", student1.name);

             printf( "Student Class : %d\n", student1.class);

             printf( "Student Section : %c\n", student1.section);

             

             return 0;

            }

Using curly braces ‘{}’

Ø  If we want to initialize all the members during the structure variable declaration, we can declare using curly braces.

Ø  Syntax:

Ø  struct stucture_name v1 = {value, value, value, ..};

Ø  To initialize the data members by this method, the comma-separated values should be provided in the same order as the members declared in the structure.

Ø  Also, this method is beneficial to use when we have to initialize all the data members.

 Example

            #include <stdio.h>

            #include <string.h>

            struct Student {

              char name[50];

              int class;

              char section;

            };

            int main() {

               struct Student student1 = {"Rakesh" , 1, 'A'};

              // printing values

              printf( "Student Name : %s\n", student1.name);

              printf( "Student Class : %d\n", student1.class);

              printf( "Student Section : %c\n", student1.section);

              return 0;

            }

Designated initializers

Ø  Designated initialization is simple initialization of the structure members and is normally used when we want to initialize only a few structure members, not all of them.

Ø  Syntax:

Ø  struct strucutre_name structure_varialbe = {.structure_member = value,.structure_member = value};

Ø  From syntax, we can see that we use curly braces, and in between them, with the help of the dot operator, data members are accessed and initialized.

Ø  There can be any number of structure members from a single structure that we can initialize, and all of them are separated using commas.

Ø  But the most important thing is that we can initialize members in any order.

Ø  It is not compulsory to maintain the same order as the members are declared in the structure.

Example

            #include <stdio.h>

            struct Student {

                 char name[50];

                 int class;

                 char section;

            };

            int main () {

                struct Student student1 = {.section = 'B', .class = 6};

                // printing values

                printf("Student1 Class is: %d\n",student1.class);

                printf("Student1 Section is: %c",student1.section);

            }

            Nested Structure

            The nested word means placed or stored one inside the other.

            As the structure in C is a user-defined data type so while creating a structure, we can define another structure as its data member, which leads to a structure with another structure inside it.

            Even the nested structure can have its nested structure.

            Syntax_1:

            struct structure_1 {

                data_member_type1 data_member_name1;

                data_member_type2 data_member_name2;

                .....

            };

            struct structure_2 {

                data_member_type data_member_name;

                ....

                ....

                struct structure_1 structure_1_variable_name;

            };

            Syntax_2:

            struct structure_2   {

                data_member_type data_member_name;

                ....

                ....

                struct structure_1    {

                    data_member_type1 data_member_name1;

                    data_member_type2 data_member_name2;

                    .....

                } structure_1_variable_name;

            };

            Program to illustrate nested structure

       1.     #include <stdio.h>

            // creating a structure

            struct Student  {

               char name[50];

               int class;

               // defining a nested structure

               struct Address  {

                   char city[50];

                   int pincode;    

               }addr;

            } student = {“Rohan", 5, “ktm", 1234};

            // variable defined with structure

            int main()

            {

               // printing values for student variable

               printf("Name : %s\nStudent City: %s",student.name,student.addr.city);

               return 0;

            }

      2.      #include <stdio.h>

            // creating a structure

            struct Subject {

               char name[50];

               char book[50];

            };

            // creating another structure with one nested structure

            struct Teacher {

               char name[50];

               // added already defined structure

               struct Subject subject;

            };

            int main() {

               // declaring variable for Teacher structure

               struct Teacher teacher;

               scanf("%s",teacher.name);

               scanf("%s",teacher.subject.name);

               scanf("%s",teacher.subject.book);

               // printing values for teacher variable

               printf("Name : %s\nBook name: %s\n",teacher.name,teacher.subject.book);

               return 0;

            }

Array of structure

Ø  Consider a case, where we need to store the data of 5 students. We can store it by using the structure S1,S2,S3,S4,S5.

Ø  However, the complexity of the program will be increased if there are 20 students.

Ø  In that case, we will have to declare 20 different structure variables and store them one by one.

Ø  This will always be tough since we will have to declare a variable every time we add a student.

Ø  Remembering the name of all the variables is also a very tricky task.

Ø  However, c enables us to declare an array of structures by using which, we can avoid declaring the different structure variables; instead we can make a collection containing all the structures that store the information of different entities.

Example

            #include<stdio.h> 

            struct student   { 

                char name[20]; 

                int id; 

                float marks; 

            }; 

            void main()   { 

                struct student s1,s2,s3;

                printf("Enter the name, id, and marks of student 1 "); 

                scanf("%s %d %f",s1.name,&s1.id,&s1.marks);

                printf("Enter the name, id, and marks of student 2 "); 

                scanf("%s %d %f",s2.name,&s2.id,&s2.marks);

                

                printf("Enter the name, id, and marks of student 3 "); 

                scanf("%s %d %f",s3.name,&s3.id,&s3.marks);

                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); 

            }

Array of structure

Ø  An array of structres in C can be defined as the collection of multiple structures variables where each variable contains information about different entities.

Ø  The array of structures in C are used to store information about multiple entities of different data types.

Ø  The array of structures is also known as the collection of structures.

 

             


       #include<stdio.h> 

            #include <string.h>   

            struct student {   

                int rollno;   

                char name[10];   

            };

            int main()  {   

                int i;   

                struct student st[5];   

                printf("Enter Records of 5 students");   

            for(i=0;i<5;i++)  {   

                 printf("\nEnter Rollno:");   

                 scanf("%d",&st[i].rollno);   

                  printf("\nEnter Name:");   

                  scanf("%s",&st[i].name);   

            }   

            printf("\nStudent Information List:");   

            for(i=0;i<5;i++)  {   

                 printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);   

            }   

             return 0;   

            }

Array within Structure

Ø  Any structure having an array as a structure member is known as an array within the structure.

Ø  We can have as many members of the type array as we want in C structure.

Ø  To access each element from an array within a structure, we write structure variables followed by dot (.) and then array name along with index.

Ø  Example: Array Within Structure

struct student {

 char name[20];

 int roll;

 float marks[5]; /* This is array within structure */

};

Ø  In previous example structure named student contains a member element marks which is of type array.

Ø  In this example marks is array of floating point numbers.

Ø  If we declare structure variable as:

Ø  struct student s;

Ø  To access individual marks from above structure s, we can write s.marks[0], s.marks[1], s.marks[2], and so on.

Array within Structure: Example

            #include<stdio.h>

            struct student {

             char name[20];

             int roll;

             float marks[5]; /* This is array within structure */

            };

            int main() {

             struct student s;

             int i;

             float sum=0, p;

             printf("Enter name and roll number of students:\n");

             scanf("%s%d",s.name,&s.roll);

             printf("\nEnter marks obtained in five different subject\n");

            for(i=0;i< 5;i++) {

              printf("Enter marks:\n");

              scanf("%f",&s.marks[i]);

              sum = sum + s.marks[i];

             }

             p = sum/5;

             printf(“Student records and percentage is:\n”);

             printf("Name : %s\n", s.name);

             printf("Roll Number : %d\n", s.roll);

             printf("Percentage obtained is: %f", p);

             return 0;

            }

Passing Structure & Array of Structure to function

Ø  To pass a structure to a function we have to properly declare the function parameter list.

Ø  In the following example we are creating a student structure.

struct student {

  char firstname[64];

  char lastname[64];

  char id[64];

  int score;

};

Ø  Now, lets say we want to create a displayDetail() function which takes the student structure variable as argument and prints the details.

 Ø  Syntax of a function declaration taking structure as argument

Ø  Following is the function declaration syntax to accept structure variable as argument.

Ø  returnType functionName(struct tagName argName);

Ø  Example:

Ø  void displayDetail(struct student std); 

Ø  To pass a structure variable to a function all we have to do is write the name of the variable and it will pass a copy of the structure variable.

Ø  In the following example code we are passing stdArr[i] variable of type student structure to the displayDetail function.

Ø  displayDetail(stdArr[i]);

Program in C to take details of 3 students as input and display the result by passing the structure to a function

#include <stdio.h>

struct student {

  char firstname[64];

  char lastname[64];

  char id[64];

  int score;

};

void displayDetail(struct student std);

int main(void) {

  struct student stdArr[3];

  int i;

for (i = 0; i < 3; i++) {

    printf("Enter detail of student #%d\n", (i+1));

    printf("Enter First Name: ");

    scanf("%s", stdArr[i].firstname);

    printf("Enter Last Name: ");

    scanf("%s", stdArr[i].lastname);

    printf("Enter ID: ");

    scanf("%s", stdArr[i].id);

    printf("Enter Score: ");

    scanf("%d", &stdArr[i].score);

  }

 

// output

  for (i = 0; i < 3; i++) {

    printf("\nStudent #%d Detail:\n", (i+1));

    displayDetail(stdArr[i]);

  }

  return 0;

}

 

void displayDetail(struct student std) {

  printf("Firstname: %s\n", std.firstname);

  printf("Lastname: %s\n", std.lastname);

  printf("ID: %s\n", std.id);

  printf("Score: %d\n", std.score);

Structure & Pointer

Ø  A structure pointer is defined as the pointer which points to the address of the memory block that stores a structure known as the structure pointer.

Ø  Complex data structures like Linked lists, trees, graphs, etc. are created with the help of structure pointers.

Ø  The structure pointer tells the address of a structure in memory by pointing the variable to the structure variable.

C program to demonstrate structure pointer

            #include <stdio.h>

            struct point {

                int value;

            };

            int main() {

                struct point s;  

                // Initialization of the structure pointer

                struct point* ptr = &s;

                return 0;

            }

Accessing the Structure Member with the Help of Pointers

Ø  There are two ways to access the members of the structure with the help of a structure pointer:

Ø  With the help of (*) asterisk or indirection operator and (.) dot operator.

Ø  With the help of ( -> ) Arrow operator.

C Program to demonstrate Structure pointer

            #include <stdio.h>

            #include <string.h>

            struct Student {

                int roll_no;

                char name[30];

                char branch[40];

                int batch;

            };

            int main() {

                struct Student s1;

                struct Student* ptr = &s1;   

                s1.roll_no = 27;

                strcpy(s1.name, “Rakesh Roshan");

                 strcpy(s1.branch, "Computer Science");

                 s1.batch = 2019;

                printf("Roll Number: %d\n", (*ptr).roll_no);

                printf("Name: %s\n", (*ptr).name);

                printf("Branch: %s\n", (*ptr).branch);

                printf("Batch: %d", (*ptr).batch);

                return 0;

            }

C Program to demonstrate Structure pointer with the help of arrow operator.

            #include <stdio.h>

            #include <string.h>

            struct Student {

                int roll_no;

                char name[30];

                char branch[40];

                int batch;

            };

            struct Student s, *ptr;

            int main() {

                ptr = &s;

                printf("Enter the Roll Number of Student\n");

                scanf("%d", &ptr->roll_no);

               printf("Enter Name of Student\n");

                scanf("%s", ptr->name);

                printf("Enter Branch of Student\n");

                scanf("%s", &ptr->branch);

                printf("Enter batch of Student\n");

                scanf("%d", &ptr->batch);

                printf("\nStudent details are: \n");

                printf("Roll No: %d\n", ptr->roll_no);

                printf("Name: %s\n", ptr->name);

                printf("Branch: %s\n", ptr->branch);

                printf("Batch: %d\n", ptr->batch);

                return 0;

            }

Dynamic memory allocation of structs

            #include <stdio.h>

            #include <stdlib.h>

            struct person {

               int age;

               float weight;

               char name[30];

            };

            int main() {

               struct person *ptr;

               int i, n;

               printf("Enter the number of persons: ");

               scanf("%d", &n)

               ptr = (struct person*) malloc(n * sizeof(struct person));

            for(i = 0; i < n; ++i) {

                   printf("Enter first name and age respectively: ");

                   scanf("%s %d", (ptr+i)->name, &(ptr+i)->age);

               }

               printf("Displaying Information:\n");

               for(i = 0; i < n; ++i)

                   printf("Name: %s\tAge: %d\n", (ptr+i)->name, (ptr+i)->age);

               return 0;

            }

Bit Fields

Ø  Suppose your C program contains a number of TRUE/FALSE variables grouped in a structure called status, as follows −

Ø  struct struct_name{

Ø     int widthValidated;

Ø     int heightValidated;

Ø  } status;

Ø  This structure requires 8 bytes of memory space but in actual, we are going to store either 0 or 1 in each of the variables.

Ø  The C programming language offers a better way to utilize the memory space in such situations.

Ø  If you are using such variables inside a structure then you can define the width of a variable which tells the C compiler that you are going to use only those number of bytes.

Ø  For example, the above structure can be re-written as follows −

Ø  struct {

Ø     int widthValidated : 1;

Ø     int heightValidated : 1;

Ø  } status;

Ø  The above structure requires 4 bytes of memory space for status variable, but only 2 bits will be used to store the values.

Ø  If you will use up to 32 variables each one with a width of 1 bit, then also the status structure will use 4 bytes.

Ø  However as soon as you have 33 variables, it will allocate the next slot of the memory and it will start using 8 bytes. Let us check the following example to understand the concept −

Bit Field Declaration

Ø  The declaration of a bit-field has the following form inside a structure −

Ø  struct struct_name {

Ø     type [member_name] : width ;

Ø  };

Ø  Where,

Ø  type: An integer type that determines how a bit-field's value is interpreted. The type may be int, signed int, or unsigned int.

Ø  member_name: The name of the bit-field.

Ø  width: The number of bits in the bit-field. The width must be less than or equal to the bit width of the specified type.

Program to illustrate bits fields

            #include <stdio.h>

            #include <string.h>

            /* define simple structure */

            struct Example{

               int widthValidated;

               int heightValidated;

            } status1;

            /* define a structure with bit fields */

            struct Example1{

               int widthValidated : 1;

               int heightValidated : 1;

            } status2;

             

            int main( ) {

               printf( "Memory size occupied by status1 : %d\n", sizeof(status1));

               printf( "Memory size occupied by status2 : %d\n", sizeof(status2));

               return 0;

            }

Bit Fields

Ø  The variables defined with a predefined width are called bit fields.

Ø  A bit field can hold more than a single bit; for example, if you need a variable to store a value from 0 to 7, then you can define a bit field with a width of 3 bits as follows −

Ø  struct {

Ø     unsigned int age : 3;

Ø  } Age;

Ø  The above structure definition instructs the C compiler that the age variable is going to use only 3 bits to store the value.

Ø  If you try to use more than 3 bits, then it will not allow you to do so.

Example

            #include <stdio.h>

            struct {

               unsigned int age : 3;

            } Age;

            int main( ) {

               Age.age = 4;

               printf( "Sizeof( Age ) : %d\n", sizeof(Age) );

               printf( "Age.age : %d\n", Age.age );

               Age.age = 7;

               printf( "Age.age : %d\n", Age.age );

               

            Age.age = 8;

               printf( "Age.age : %d\n", Age.age );

               return 0;

            }

Union

Ø  union is a special data type available in C that allows to store different data types in the same memory location.

Ø  You can define a union with many members, but only one member can contain a value at any given time.

Ø  A union is a user-defined type similar to structs in C except for one key difference.

Ø  Structures allocate enough space to store all their members, whereas unions can only hold one member value at a time.

Ø  Unions provide an efficient way of using the same memory location for multiple-purpose.

Ø  The memory occupied by a union will be large enough to hold the largest member of the union.

Example

            #include <stdio.h>

            #include <string.h>

            union Data {

               int i;

               float f;

               char str[20];

            };

            int main( ) {

               union Data data;  

               data.i = 10;

               data.f = 220.5;

               strcpy( data.str, "C Programming");

               printf( "data.i : %d\n", data.i);

               printf( "data.f : %f\n", data.f);

               printf( "data.str : %s\n", data.str);

               return 0;

            }

            #include <stdio.h>

            #include <string.h>

            union Data {

               int i;

               float f;

               char str[20];

            };

            int main( ) {

               union Data data;  

               data.i = 10;

               printf( "data.i : %d\n", data.i);

               data.f = 220.5;

               printf( "data.f : %f\n", data.f);

               strcpy( data.str, "C Programming");

               printf( "data.str : %s\n", data.str);

               return 0;

            }

Importance of Union

Ø  C unions are used to save memory.

Ø  When we want to assign a new value to a field, then the existing data is replaced with new data.

Ø  C unions allow data members which are mutually exclusive to share the same memory.

Ø  This is quite important when memory is valuable, such as in embedded systems.

Ø  Unions are mostly used in embedded programming where direct access to the memory is needed.

Structure vs. Union


            #include <stdio.h>

            union unionJob {

               //defining a union

               char name[32];

               float salary;

               int workerNo;

            } uJob;

            struct structJob {

               char name[32];

               float salary;

               int workerNo;

            } sJob;

            int main() {

               printf("size of union = %d bytes", sizeof(uJob));

               printf("\nsize of structure = %d bytes", sizeof(sJob));

               return 0;

            }

WAP to enter name, salary and age of 10 employee into structure variable called employee and sort them in ascending order on the basis of their name.

            #include<stdio.h>

            #include<string.h>

            struct employee {

             char name[30];

             int salary;

             int age;

            };

            int main() {

             struct employee e[20], temp;

             int i,j,n;

             printf("Enter n:\n");

             scanf("%d",&n);

            for(i=0;i< n;i++) {

              printf("Enter name, salary and age of employee:\n");

              scanf("%s%d%d",e[i].name, &e[i].salary, &e[i].age);

             }

             for(i=0;i< n-1;i++) {

              for(j=i+1;j< n;j++)  {

               if(strcmp(e[i].name, e[j].name) > 0) {

                temp = e[i];

                e[i] = e[j];

                e[j] = temp;

               }  }

             }

            printf("Records in alphabetical order are:\n");

             for(i=0;i< n;i++) {

              printf("Name: %s\n", e[i].name);

              printf("Salary: %d\n", e[i].salary);

              printf("Age: %d\n\n", e[i].age);

             }

             return 0;

            }

WAP to enter name, salary and age of 10 employee into structure variable called employee and sort them in ascending order on the basis of their name with use of pointer.

#include<stdio.h>

#include<string.h>

#include<Stdlib.h>

struct employee {

 char name[30];

 int salary;

 int age;

};

int main()  {

 struct employee *e, temp;

 int i,j,n;

 printf("Enter number of employee:\n");

 scanf("%d",&n);

e = (struct employee*)malloc(n* sizeof(struct employee));

 for(i=0;i< n;i++) {

     printf("Enter name, salary and age of employee:\n");

     scanf("%s%d%d",(e+i)->name, &(e+i)->salary, &(e+i)->age);

 }

 for(i=0;i< n-1;i++) {

  for(j=i+1;j< n;j++)  {

   if(strcmp((e+i)->name, (e+j)->name) > 0) {

    temp = *(e+i);

    *(e+i) = *(e+j);

    *(e+j) = temp;

   }  }  }

            printf("Records in alphabetical order are:\n");

             for(i=0;i< n;i++) {

              printf("Name: %s\n", (e+i)->name);

              printf("Salary: %d\n", (e+i)->salary);

              printf("Age: %d\n\n", (e+i)->age);

             }

             return 0;

            }

 

 

 

 

 

 

 

 

             

 

 

 

No comments:

Post a Comment

Research in Social Science

   C  Concept of Research in Social Science -         Understanding the concept of Research Methods, Techniques and Tools: Interview, Fo...