Structures in C

A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. How to create a structure?

‘struct’ keyword is used to create a structure. Following is an example.

struct address
{
   char name[50];
   char street[100];
   char city[50];
   char state[20];
   int pin;
};

What is Structure :

Structure in c is a user-defined data type that enables us to store the collection of different data types. Each element of a structure is called a member. Structures ca; simulate the use of classes and templates as it can store various information

The ,struct keyword is used to define the structure. Let’s see the syntax to define the structure in c.

 
  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

 

Declaring structure variable :

We can declare a variable for the structure so that we can access the member of the structure easily. There are two ways to declare structure variable:

By struct keyword within main() function
By declaring a variable at the time of defining the structure.
1st way:

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

write given code inside the main() function.

struct employee e1, e2;

The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2 can be treated in the same way as the objects in C++ and Java.

2nd way:

Let’s see another way to declare variable at the time of defining the structure.

struct employee
{
int id;
char name[50];
float salary;
}e1,e2;

Which approach is good ?

If number of variables are not fixed, use the 1st approach. It provides you the flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in main() function.

  1. #include<stdio.h>  
  2. #include <string.h>    
  3. struct employee      
  4. {   int id;      
  5.     char name[50];      
  6. }e1;  //declaring e1 variable for structure    
  7. int main( )    
  8. {    
  9.    //store first employee information    
  10.    e1.id=101;    
  11.    strcpy(e1.name, “Sonoo Jaiswal”);//copying string into char array    
  12.    //printing first employee information    
  13.    printf( “employee 1 id : %d\n”, e1.id);    
  14.    printf( “employee 1 name : %s\n”, e1.name);    
  15. return 0;  
  16. }    

Output:

employee 1 id : 1
employee 1 name : ccatcracker

Lets Do Some exercises on Structure dont copy code from google :

1. C Program to Store Information of a Student Using Structure .

Format :

Enter information:
Enter name: abc
Enter roll number: 23
Enter marks: 34
Output :

Name: abc
Roll number: 23
Marks: 34


Big Case Study Whatever we learnt so far will cover in this assignment :

2.Write a C program to keep records and perform statistical analysis for a class of 20 students. The information of each student contains ID, Name, Sex, quizzes Scores (2 quizzes per semester), mid-term score, final score, and total score. The program will prompt the user to choose the operation of records from a menu as shown below:

Structure of Your Code Will look Like :
============================================
Menu


============================================
1. Add student records
2. Delete student records
3. Update student records
4. View all student records
5. Calculate an average of a selected student’s scores
6. Show student who gets the max total score
7. Show student who gets the min total score
8. Find student by ID
9. Sort records by total scores

Enter your choice:4
So I ennter choice is 4 so our code will display all students records ..
Its really very tough assignment if you can solve this means you are at good position .
Try hard ..

What is Union

Union is a user-defined type similar to a structure in C programming. We recommend you to learn about C structures before you check this article. We use union keyword to define unions. Here’s an example:

 union car
                                    {
                                      char name[50];
                                      int price;
                                    };

 

The above code defines a derived type union car.

 

Create union variables :

When a union is defined, it creates a user-defined type. However, no memory is allocated. To allocate memory for a given union type and work with it, we need to create variables.

Here’s how we create union variables:

                                union car
                                    {
                                      char name[50];
                                      int price;
                                    };
                                    
                                    int main()
                                    {
                                      union car car1, car2, *car3;
                                      return 0;
                                    }
                            

 

How to access members of a union? :

We use . to access normal variables of a union. To access pointer variables, we use -> operator.

In the above example,

price for car1 can be accessed using car1.price
price for car3 can be accessed using car3->price

Difference between unions and structures :

Let’s take an example to demonstrate the difference between unions and structures:

  1. #include <stdio.h>
  2. union unionJob
  3. {
  4. //defining a union
  5. char name[32];
  6. float salary;
  7. int workerNo;
  8. } uJob;
  9. struct structJob
  10. {
  11. char name[32];
  12. float salary;
  13. int workerNo;
  14. } sJob;
  15. int main()
  16. {
  17. printf("size of union = %d bytes", sizeof(uJob));
  18. printf("\nsize of structure = %d bytes", sizeof(sJob));
  19. return 0;
  20. }



Output :

size of union = 32
size of structure = 40

Why this difference in size of union and structure variables?



The size of structure variable is 40 bytes. It’s because:

size of name[32] is 32 bytes
size of salary is 4 bytes
size of workerNo is 4 bytes
However, the size of union variable is 32 bytes. It’s because the size of union variable will always be the size of its largest element. In the above example, the size of largest element (name[32]) is 32 byes.