0% found this document useful (0 votes)
494 views

C Programming UNIT 4.3 Structure and Union

Structure is a user-defined data type that allows grouping of different data types under a single name in C. A structure creates a new data type consisting of fields of different data types. Structures can be used to store records of different entities like student, employee etc. An array of structures allows storing information of multiple entities by defining a collection of structure variables. Structures and arrays of structures provide a cleaner way to organize related data in C as compared to using multiple individual variables.

Uploaded by

rishika
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
494 views

C Programming UNIT 4.3 Structure and Union

Structure is a user-defined data type that allows grouping of different data types under a single name in C. A structure creates a new data type consisting of fields of different data types. Structures can be used to store records of different entities like student, employee etc. An array of structures allows storing information of multiple entities by defining a collection of structure variables. Structures and arrays of structures provide a cleaner way to organize related data in C as compared to using multiple individual variables.

Uploaded by

rishika
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

STRUCTURE AND UNION

Introduction
In C language, to store the integers, characters, decimal values, we have int, char, float, or
double data types already defined (also known as the primitive data types). Also, we have some
derived data types such as arrays and strings, to store similar types of data types elements
together. Still, the problem with arrays or strings is that they can only store variables of similar
data types, and the string can store only characters. What if we need to store two different data
types together in C for many objects? Like, there is a student variable that may have its name,
class, section, etc. So if we want to store all of its information, We can create different variables
for every variable like a character array to store name, integer variable to store the class, and a
character variable to store the section. But this solution is a little messy, C provides us with a
better neat and clean solution, i.e., Structure.

What is Structure
Structure 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.

The struct keyword is used to define the structure. Let's see the syntax to define the structure
in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

Let's see the example to define a structure for an entity employee in c.


struct employee
{ int id;
char name[20];
float salary;
};

The following image shows the memory allocation of the structure employee that is defined in
the above example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the
members or fields of the structure. Let's understand it by the diagram given below:

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:
1. By struct keyword within main() function
2. 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;
};

Now 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.

Accessing members of the structure


There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)

Accessing structure members using the dot operator


#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
e1.id=101; //store first employee information
strcpy(e1.name, "Sonoo Jaiswal"); //copying string into char array
printf( "employee 1 id : %d\n", e1.id); //printing first employee information
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal

Let's see another example of the structure in C language to store many employees information.
#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


printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);

//printing second employee information


printf( "employee 2 id : %d\n", e2.id);
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
return 0;
}

Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Accessing structure members using the arrow operator


Another way to access structure members in C is using the (->) operator. Using this way, we
don't need an asterisk and dot operator with the pointer. To access members of the structure
using (->) operator we write pointer name with -> followed by the name of the member that
is
pointer_name->member_name

Let us see an example to understand how we can use an arrow operator to access structure
members using structures and pointers in C.

#include<stdio.h>

struct Student {
char name[30];
int age;
int roll_number;
};

int main() {
struct Student student_1;
struct Student *sp = &student_1;

printf ("Enter the details of the Student (student_1)\n");


printf ("\tName: ");
scanf ("%s", sp->name);
printf ("\tAge: ");
scanf ("%d", &sp->age);
printf ("\tRoll Number: ");
scanf ("%d", &sp->roll_number);

printf ("\n Display the details of the student_1 using Structure Pointer\n");
printf ("\tName: %s\n", sp->name);
printf ("\tAge: %d\n", sp->age);
printf ("\tRoll Number: %d", sp->roll_number);

return 0;
}

Output

Enter the details of the Student (student_1)


Name: Scalar
Age: 18
Roll Number: 1747

Display the details of the student_1 using Structure Pointer


Name: Scalar
Age: 18
Roll Number: 1747

Accessing members of the structure using the membership operator on structure pointer
makes code more readable when compared to the other approach.

C Array of Structures

Why use an array of structures?


Consider a case, where we need to store the data of 5 students. We can store it by using the
structure as given below.
#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
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000

In the above program, we have stored data of 3 students in the structure. 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.

Array of Structures in C

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.
Let's see an example of an array of structures that stores information of 5 students and prints
it.
#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;
}

Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
How to pass struct variables as arguments to a function

#include <stdio.h>
struct student {
char name[50];
int age;
};

void display(struct student s); // function prototype


int main() {
struct student s1;

printf("Enter name: ");


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

printf("Enter age: ");


scanf("%d", &s1.age);

display(s1); // passing struct as an argument

return 0;
}

void display(struct student s) {


printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}

Output

Enter name: Bond


Enter age: 13

Displaying information
Name: Bond
Age: 13

Here, a struct variable s1 of type struct student is created. The variable is passed to
the display() function using display(s1); statement.

UNION:
In C, a union is a user-defined data type that allows many different data types to be stored in
the same memory region. A union can have numerous members, but only one of them can
occupy the memory at any one moment. Unions allow developers to optimize memory usage
while declaring variables.
They are conceptually similar to structures. The syntax to define a union is also similar to that
of a structure. The only difference is in terms of storage. In a structure, each member has its
own storage location, whereas all members of a union use a single shared memory location,
which is equal to the size of its largest data member.
How to Define a Union?
union student
{
char name[50];
int roll number;
};

How to Create a Union Variable?


When a union is represented, it makes a user-defined type. Nevertheless, in this condition, no
memory is assigned. To assign the memory, we ought to build variables.
Let’s see how we can construct variables:
union student
{
char name[50];
int roll number;
};
int main()
{
union student stu1, stu2, *stu3;
return 0;
}
There is one more aspect of creating a union variable:
union student
{
char name[50];
int roll number;
} stu1, stu2, *stu3;

Accessing a Member in Union


#include <stdio.h>
Union School{
float percentage;
int studentNo;
} j;
int main() {
j.percentage = 12.3;
// when j.student No is assigned a value,
// j.percentage will no longer hold 12.3
j.workerNo = 100;
printf(“Percentage = %.1f\n”, j.pPercentage);
printf(“Number of students= %d”, j.studentNo);
return 0;
}

Output of the Above Code:


Percentage= 0.0
Number of Students= 100
Similarities between Structure and Union
1. Both are user-defined data types used to store data of different types as a single unit.
2. Their members can be objects of any type, including other structures and unions
or arrays. A member can also consist of a bit field.
3. Both structures and unions support only assignment = and sizeof operators. The two
structures or unions in the assignment must have the same members and member
types.
4. A structure or a union can be passed by value to functions and returned by value by
functions. The argument must have the same type as the function parameter.
5. ‘.’ operator or selection operator is used for accessing member variables inside both
the user-defined datatypes.

Differences between Structure and Union

You might also like