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

C Structure & Union - Module IV

Uploaded by

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

C Structure & Union - Module IV

Uploaded by

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

C Programming

Module IV

Mrs.A.Reshma Parveen
Structures

Mrs.A.Reshma Parveen
C Structure
Why use structure?

• In C, there are cases where we need to store multiple attributes of an entity. It is not necessary that

an entity has all the information of one type only. It can have different attributes of different data

types. For example, an entity Student may have its name (string), roll number (int), marks (float). To

store such type of information regarding an entity student, we have the following approaches:

• Construct individual arrays for storing names, roll numbers, and marks.

• Use a special data structure to store the collection of different data types.

Mrs.A.Reshma Parveen
C Structure
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 can 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.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

Mrs.A.Reshma Parveen
C Structure
What is Structure

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

struct employee

{ int id;

char name[20];

float salary;

};

Mrs.A.Reshma Parveen
C Structure

Mrs.A.Reshma Parveen
C Structure
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:

Mrs.A.Reshma Parveen
C Structure
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.

Mrs.A.Reshma Parveen
C 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

Mrs.A.Reshma Parveen
C Structure
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.

Mrs.A.Reshma Parveen
C Structure
Accessing members of the structure

There are two ways to access structure members:

By . (member or dot operator)

By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by. (member) operator.

p1.id

Mrs.A.Reshma Parveen
C Structure
C Structure example
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}; //declaring e1 variable for structure
int main( )
{ struct employee e1;
//store first employee information
printf(“Enter id and name:\n”);
scanf( ”%d”,&e1.id);
scanf(“%s”,&e1.name);
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Mrs.A.Reshma Parveen
C Structure
C Structure example
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}

Mrs.A.Reshma Parveen
C Structure
Let's see another example of the structure in C language to //store second employee information
store many employees information. e2.id=102;
#include<stdio.h> strcpy(e2.name, "James");
#include <string.h> e2.salary=126000;
struct employee
{ int id; //printing first employee information
char name[50]; printf( "employee 1 id : %d\n", e1.id);
float salary; printf( "employee 1 name : %s\n", e1.name);
}e1,e2; //declaring e1 and e2 variables for structure printf( "employee 1 salary : %f\n", e1.salary);
int main( )
{ //printing second employee information
//store first employee information printf( "employee 2 id : %d\n", e2.id);
e1.id=101; printf( "employee 2 name : %s\n", e2.name);
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char printf( "employee 2 salary : %f\n", e2.salary);
array return 0;
e1.salary=56000; }

Mrs.A.Reshma Parveen
C Structure Pointer
To access members of a structure using pointers, we use the -> operator
#include <stdio.h>
struct person printf("Displaying:\n");
{ printf("Age: %d\n", personPtr->age);
int age; printf("weight: %f", personPtr->weight);
float weight;
return 0;
}; }

int main()
{
struct person *personPtr, person1;
In this example, the address of person1 is stored in the personPtr
personPtr = &person1;
pointer using personPtr = &person1;.

printf("Enter age: "); Now, you can access the members of person1 using the personPtr
scanf("%d", &personPtr->age); pointer.By the way,

printf("Enter weight: "); personPtr->age is equivalent to (*personPtr).age


scanf("%f", &personPtr->weight); personPtr->weight is equivalent to (*personPtr).weight
Mrs.A.Reshma Parveen
typedef in C
The typedef is a keyword used in C programming to provide some meaningful names to the already existing
variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say
that this keyword is used to redefine the name of an already existing variable.
Syntax of typedef
typedef <existing_name> <alias_name>
In the above syntax, 'existing_name' is the name of an already existing variable while 'alias name' is another
name given to the existing variable.
For example, suppose we want to create a variable of type unsigned int, then it becomes a tedious task if we
want to declare multiple variables of this type. To overcome the problem, we use a typedef keyword.
typedef unsigned int unit;

Mrs.A.Reshma Parveen
typedef in C
In the above statements, we have declared the unit variable of type unsigned int by using a

typedef keyword.

Now, we can create the variables of type unsigned int by writing the following statement:

unit a, b;

instead of writing:

unsigned int a, b;

Till now, we have observed that the typedef keyword provides a nice shortcut by providing an alternative

name for an already existing variable. This keyword is useful when we are dealing with the long data type

especially, structure declarations.


Mrs.A.Reshma Parveen
typedef in C
Let's understand through a simple example.
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
Mrs.A.Reshma Parveen
typedef in C
Using typedef with structures
Consider the below structure declaration:
struct student
{
char name[20];
int age;
};
struct student s1;
In the above structure declaration, we have created the variable of student type by writing the following
statement:
struct student s1;

Mrs.A.Reshma Parveen
typedef in C
The above statement shows the creation of a variable, i.e., s1, but the statement is quite big. To avoid such a
big statement, we use the typedef keyword to create the variable of type student.
struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;
In the above statement, we have declared the variable stud of type struct student. Now, we can use
the stud variable in a program to create the variables of type struct student.

Mrs.A.Reshma Parveen
typedef in C
The above typedef can be written as:

typedef struct student

char name[20];

int age;

} stud;

stud s1,s2;

From the above declarations, we conclude that typedef keyword reduces the length of the code and

complexity of data types. It also helps in understanding the program.


Mrs.A.Reshma Parveen
typedef in C
Let's see another example where we typedef the structure declaration.
#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
int main()
{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",&s1.name);
printf("\nEnter the age of student:");
scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
return 0;
}
Mrs.A.Reshma Parveen
Array of Structures
Why use an array of structures?
#include<stdio.h> printf("Enter the name, id, and marks of student 3 ");
struct student scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
scanf("%c",&dummy);
{
printf("Printing the details....\n");
char name[20]; printf("%s %d %f\n",s1.name,s1.id,s1.marks);
int id; printf("%s %d %f\n",s2.name,s2.id,s2.marks);
float marks; printf("%s %d %f\n",s3.name,s3.id,s3.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);
Mrs.A.Reshma Parveen
Array of Structures
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.

Mrs.A.Reshma Parveen
Array of Structures
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.

Mrs.A.Reshma Parveen
Array 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;
}
Mrs.A.Reshma Parveen
Nested Structure
Nested Structure in C

C provides us the feature of nesting one structure within another structure by using which, complex data

types are created. For example, we may need to store the address of an entity employee in a structure. The

attribute address may also have the subparts as street number, city, state, and pin code. Hence, to store the

address of the employee, we need to store the address of the employee into a separate structure and nest

the structure address into the structure employee

Mrs.A.Reshma Parveen
Nested Structure
The structure can be nested in the following ways.
1.By separate structure
2.By Embedded structure
1) Separate structure
Here, we create two structures, but the dependent structure should be used inside the main structure as a
member. Consider the following example.
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee
structure. In this way, we can use Date structure in many structures.
Mrs.A.Reshma Parveen
Nested Structure
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}
Mrs.A.Reshma Parveen
Nested Structure
2) Embedded structure
The embedded structure enables us to declare the structure inside the structure. Hence, it requires less line
of codes but it can not be used in multiple data structures. Consider the following example.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;

Mrs.A.Reshma Parveen
Nested Structure
Accessing Nested Structure

We can access the member of the nested structure by Outer_Structure.Nested_Structure.member as given

below:

e1.doj.dd

e1.doj.mm

e1.doj.yyyy

Mrs.A.Reshma Parveen
Nested Structure
C Nested Structure example int main( )
{
#include <stdio.h> //storing employee information
#include <string.h> e1.id=101;
struct Employee strcpy(e1.name, "Sonoo Jaiswal");//copying string into
{ char array
int id; e1.doj.dd=10;
char name[20]; e1.doj.mm=11;
struct Date e1.doj.yyyy=2014;
{
int dd; //printing first employee information
int mm; printf( "employee id : %d\n", e1.id);
int yyyy; printf( "employee name : %s\n", e1.name);
}doj; printf( "employee date of joining (dd/mm/yyyy) : %d/%
}e1; d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
return 0;
}

Mrs.A.Reshma Parveen
Passing structure to function
Just like other variables, a structure can also be passed to a function. We may pass the structure members
into the function or pass the structure variable at once. Consider the following example to pass the structure
variable employee to a function display() which is used to display the details of an employee.
#include<stdio.h> void main ()
struct address {
{ struct employee emp;
char city[20]; printf("Enter employee information?\n");
int pin; scanf("%s %s %d %s",emp.name,emp.add.city, &emp.a
char phone[14]; dd.pin, emp.add.phone);
}; display(emp);
struct employee }
{ void display(struct employee emp)
char name[20]; {
struct address add; printf("Printing the details....\n");
}; printf("%s %s %d %s",emp.name,emp.add.city,emp.add.
void display(struct employee); pin,emp.add.phone);
}

Mrs.A.Reshma Parveen
Union

Mrs.A.Reshma Parveen
Union in C
Union can be defined as a user-defined data type which is a collection of different variables of different data
types in the same memory location. The union can also be defined as many members, but only one member
can contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory location.
Let's understand this through an example.
struct abc
{
int a;
char b;
}

Mrs.A.Reshma Parveen
Union in C
The above code is the user-defined structure that consists of two members, i.e., 'a' of type int and 'b' of

type character. When we check the addresses of 'a' and 'b', we found that their addresses are different.

Therefore, we conclude that the members in the structure do not share the same memory location.

When we define the union, then we found that union is defined in the same way as the structure is defined

but the difference is that union keyword is used for defining the union data type, whereas the struct keyword

is used for defining the structure. The union contains the data members, i.e., 'a' and 'b', when we check the

addresses of both the variables then we found that both have the same addresses. It means that the union

members share the same memory location.

Mrs.A.Reshma Parveen
Union in C
Let's understand this concept through an example.

union abc
{
int a;
char b;
}var;
int main()
{
var.a = 66;
printf("\n a = %d", var.a);
printf("\n b = %c", var.b);
}

In the above code, union has two members, i.e., 'a' and 'b'. The 'var' is a variable of union abc type. In
the main() method, we assign the 66 to 'a' variable, so var.a will print 66 on the screen. Since both 'a' and 'b'
share the memory location, var.b will print 'B' (ascii code of 66).

Mrs.A.Reshma Parveen
Union in C
Deciding the size of the union
The size of the union is based on the size of the largest member of the union.
Let's understand through an example.
union abc{
int a;
char b;
float c;
double d;
};
int main()
{
printf("Size of union abc is %d", sizeof(union abc));
return 0;
}
As we know, the size of int is 4 bytes, size of char is 1 byte, size of float is 4 bytes, and the size of double is 8
bytes. Since the double variable occupies the largest memory among all the four variables, so total 8 bytes
will be allocated in the memory. Therefore, the output of the above program would be 8 bytes.

Mrs.A.Reshma Parveen
Union in C
Accessing members of union using pointers
We can access the members of the union through pointers by using the (->) arrow operator.
Let's understand through an example.
#include <stdio.h>
union abc
{
int a;
char b;
};
int main()
{
union abc *ptr; // pointer variable declaration
union abc var;
var.a= 90;
ptr = &var;
printf("The value of a is : %d", ptr->a);
return 0;
}
In the above code, we have created a pointer variable, i.e., *ptr, that stores the address of var variable. Now, ptr
can access the variable 'a' by using the (->) operator. Hence the output of the above code would be 90.
Mrs.A.Reshma Parveen
Structure Vs Union

Mrs.A.Reshma Parveen
Structure Vs Union

Mrs.A.Reshma Parveen

You might also like