0% found this document useful (0 votes)
17 views60 pages

Unit 8 Structure & Union - Lecture

The document provides an overview of structures and unions in C programming, detailing their definitions, types, and usage. It explains how to declare, initialize, and access structure members, as well as the concept of nested structures and arrays of structures. Additionally, it covers pointers to structures and their memory allocation, along with example programs for practical understanding.

Uploaded by

sandinaneupane4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views60 pages

Unit 8 Structure & Union - Lecture

The document provides an overview of structures and unions in C programming, detailing their definitions, types, and usage. It explains how to declare, initialize, and access structure members, as well as the concept of nested structures and arrays of structures. Additionally, it covers pointers to structures and their memory allocation, along with example programs for practical understanding.

Uploaded by

sandinaneupane4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Unit 8: Structure and Union

Outlines
 Definition of Structure
 Nested type Structure
 Array of Structure
 Structure & Pointers
 Unions
 Self – referential Structure

1
Structure and Union
Data Types
In C programming language divide data into
the different types. The various data types are:

 Simple Data type (Fundamental)


Integer, float Void, Char
 Structured Data type (Derived)
Array, Strings
 User Defined Data type (Programmer)
Enum, Structures, Unions

2
Structure Concept

Problem:
– How to group together a collection of data items
of different types that are logically related to a
particular entity??? (Array)
Solution: Structure

3
Structure Introduction
Structure Data Type
1. User defined data type
2. Groups logically related data items of different data
types into a single unit.
3. All the elements of a structure are stored at contiguous
memory locations.
4. A variable of structure type can store multiple data
items of different data types under the one name.
5. As the data of employee in company that is name,
Employee ID, salary, address, phone number is stored
in structure data type.
4
Example of Structure

The structure of Employee is declared


as,

struct employee
{
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int age;
};
55
Structure of employee
Memory Space Allocation
8000 emp_id
8002 name[20]

8022 salary
8024 address[50]

8074 dept_no
8076 age
6
Structure
Declaring a Structure Variable
The syntax of declaring a structure is
struct <struct_name> <variable_name>;
For e.g,
If we declare “employee” as structure:
struct employee e1;
Here e1 is a structure variable.

7
Defining a structure…
• The structure definition and The use of structure_name is
variable declaration can be optional.
combined as: struct
struct student {
{ char name[20];
char name[20]; int roll_no;
int roll_no; float marks;
float marks; char gender;
char gender; long int phone_no;
long int phone_no; }
} st1, st2, st3;
st1, st2, st3;

8
Example of Structure
The structure of student is declared as,

struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
};
struct student st;

• Multiple variables of struct student type can be declared as:


struct student st1, st2, st3; 9
Accessing a Structure Members
1. The structure members cannot be directly accessed in the
expression.
2. They are accessed by using the name of structure variable
followed by a dot and then the name of member
variable.
3. For example: e1.emp_id, e1.name, e1.salary, e1.address,
e1.dept_no, e1.age.
4. The data within the structure is stored and printed by this
method using scanf and printf statement in c program.

10
Structure initialization
• Syntax:

struct structure_name structure_variable = { value1, value2, … ,


valueN };

11
How to access & initialize Structure
Initializing a Structure Members
The members of individual structure variable is
initialize one by one or in a single statement.
The example to initialize a structure variable is
struct employee e1 =
{1, “Suresh”,12000, “damak jhapa”,10, 35};

e1.emp_id=1; e1.dept_no=10;
e1.name=“Suresh”; e1.age=35;
e1.salary=12000;
e1.address=“damak jhapa”;
12
Example OUTPUT
Name Roll No. Marks Gender Phone No.
#include<stdio.h>
ABC 4 79.5 M 5010670
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
};
int main()
{
struct student st1={"ABC", 4, 79.5, 'M', 5010670};
printf("Student details:\n");
printf("Name\t Roll No.\t Marks\t Gender\t Phone No.");
printf("\n %s\t % d\t\t %.1f\t %c\t %ld", st1.name, st1.roll_no, st1.marks,
st1.gender, st1.phone_no);
return 0;
}
13
C program to create, declare and initialize
structure
#include <stdio.h>
OUTPUT
/*structure declaration*/ Name: Milan
struct employee{ Id: 1120
char name[30]; Salary: 76909.50
int empId;
float salary;
};

int main()
{
/*declare and initialization of structure variable*/
struct employee emp={"Milan",1120,76909.5};
printf("Details:\n");
printf("\n Name: %s",emp.name);
printf("\n Id: %d",emp.empId);
printf("\n Salary: %.2f\n",emp.salary);
return 0;
}
14
C program to read and print an employee's detail
using structure
#include <stdio.h> /*print employee details*/
/*structure declaration*/ printf("\n...................................\n");
struct employee{
char name[30]; printf("Entered detail is:\n");
int empId;
printf("Name: %s\n",emp.name);
float salary;
printf("Id: %d\n",emp.empId);
};
int main() printf("Salary: %.2f",emp.salary);
{ return 0;
/*declare structure variable*/ }
struct employee emp; OUTPUT
Enter details :
/*read employee details*/ Enter Name:Rama
printf("\nEnter details :\n"); Enter ID:101
printf("Enter Name:"); Enter Salary:45566.556
gets(emp.name); Entered detail is:
printf("Enter ID:"); Name: Rama
scanf("%d",&emp.empId); Id: 101
printf("Enter Salary:"); Salary: 45566.55
scanf("%f",&emp.salary); 15
Question
• Create a structure named student that has name, roll and
mark as members.
• Assume appropriate types and size of member.
• Write a program using structure to read and display the data
entered by the user.

16
#include<stdio.h> Program
struct student
{
char name[20]; OUTPUT
int roll; Enter name: Ram
float mark;
}; Enter roll: 21
int main()
Enter marks: 59.7
{
struct student s; Name Roll Mark
printf("Enter name:\t");
gets(s.name); ...................................
printf("\n Enter roll:\t");
scanf("%d", &s.roll); Ram 21 59.700001
printf("\n Enter marks:\t"); --------------------------------
scanf("%f", &s.mark);
printf("\n Name \t Roll \t Mark\n");
printf("\n...................................\n");
printf("\n%s\t%d\t%f ", s.name, s.roll, s.mark);
return 0;
} 17
Structure within another Structure
(Nested Structure)
 Structure within structure is called Nested Structure
 One structure can be declared inside other structure as we
declare structure members inside a structure.
 The structure variables can be a normal structure variable or
a pointer variable to access the data.

Methods
1. Structure within structure using normal variable
2. Structure within structure using pointer variable

18
Structure within another Structure
(Nested Structure)
1. Structure within structure using normal variable:

 This program explains how to use structure within structure in C using


normal variable.
 “college_detail” structure is declared inside “student_detail” structure in
this program.
 Both structure variables are normal structure variables.
 Note that members of “college_detail” structure are accessed by double
dot(.) operator and members of “student_detail” structure are accessed
by single dot(.) operator.

19
#include <stdio.h>
#include <string.h>
struct college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct college_detail clg_data;
}
stu_data;
int main()
{
struct student_detail stu_data = {1, "Ramesh", 90.5, 71145,"Pokhara University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);
printf(" College Id is: %d \n", stu_data.clg_data.college_id);
printf(" College Name is: %s \n",stu_data.clg_data.college_name);
return 0;
} 20
Structure within another Structure
(Nested Structure)
1. Structure within structure in C using normal variable:

OUTPUT

Id is: 1
Name is: Ramesh
Percentage is: 90.500000

College Id is: 71145


College Name is: Pokhara University

21
Structure within another Structure
(Nested Structure)
2. Structure within structure (nested structure in C ) using pointer variable:

 This program explains how to use structure within structure in C using


pointer variable. “college_detail’ structure is declared inside
“student_detail” structure in this program.
 One normal structure variable and one pointer structure variable is used in
this program.

Note that combination of .(dot) and ->(arrow) operators are used to access
the structure member which is declared inside the structure.

22
#include <stdio.h>
#include <string.h>
struct college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct college_detail clg_data;
}
stu_data, *stu_data_ptr;

int main()
{
struct student_detail stu_data = {1, "Ram", 90.5, 71145, "Pokhara University"};
stu_data_ptr = &stu_data;
printf(" Id is: %d \n", stu_data_ptr->id);
printf(" Name is: %s \n", stu_data_ptr->name);
printf(" Percentage is: %f \n\n", stu_data_ptr->percentage);
printf(" College Id is: %d \n", stu_data_ptr->clg_data.college_id);
printf(" College Name is: %s \n", stu_data_ptr->clg_data.college_name); 23
return 0; }
Output:

Structure within another Structure


(Nested Structure)
2. Structure within structure (nested structure in C ) using pointer variable:

OUTPUT

Id is: 1
Name is: Ram
Percentage is: 90.500000
College Id is: 71145
College Name is: Pokhara University

24
• Create a structure named date that has day,
month and year as its members. Include this
structure as a member in another structure
named employee which has name, id and
salary as other members. Use this structure
to read and display employee’s name, id,
date of birthday and salary.

25
Array of Structure
1. The array of structure is used to store the
large number of similar records.
2. For example to store the record of 100 employees then array of
structure is used.
3. This is similar to array.
4. The syntax to define the array of structure is
struct <struct_name> <var_name(array_name)> [<value>];
For Example:-
struct employee e1[100];

26
Array of structure
• Let us consider we have a structure as:
struct student
{
char name[20];
int roll;
char remarks;
float marks;
};

• If we want to keep record of 100 students, we have to make 100


structure variables like st1, st2, …,st100.

• In this situation we can use array of structure to store the records of


100 students which is easier and efficient to handle (because loops
can be used). 27
Array of structure…
• Two ways to declare an
array of structure:

struct student struct student


{ {
char name[20]; char name[20];
int roll; int roll;
char remarks; char remarks;
float marks; float marks;
} };
st[100]; struct student st[100];
28
Array of structure…
Example program for array of structures in C:

 WAP to store and access “id, name and percentage” for 3 students.
 Structure array is used in this program to store and display records
for many students.
 We can store “n” number of students record by declaring structure
variable as “struct student record[n]”, where n can be 1000 or 5000
etc.

29
Array of structure…
Example program for array of structures in C:
// 2nd student's record initialization
#include <stdio.h> record[1].id=2;
#include <string.h> strcpy(record[1].name, "Suresh");
struct student record[1].percentage = 90.5;
{
// 3rd student's record initialization
int id; record[2].id=3;
char name[30]; strcpy(record[2].name, "Radha");
float percentage; record[2].percentage = 81.5;
};

int main() for(i=0; i<3; i++)


{ {
int i; printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
struct student record[2]; printf(" Name is: %s \n", record[i].name);
printf(" Percentage is:
// 1st student's record initialization %f\n\n",record[i].percentage);
record[0].id=1; }
strcpy(record[0].name, "Madan"); return 0; }
record[0].percentage = 86.5;
30
Array of structure…
Example program for array of structures in C:

OUTPUT

Records of STUDENT : 1
Id is: 1
Name is: Madan
Percentage is: 86.500000

Records of STUDENT : 2
Id is: 2
Name is: Suresh
Percentage is: 90.500000

Records of STUDENT : 3
Id is: 3
Name is: Radha
Percentage is: 81.500000
31
Pointer to Structure
• A structure type pointer variable can be declared as:
struct book
{
char name[20];
int pages;
float price;
};
struct book *bptr;

• However, this declaration for a pointer to structure does not allocate any memory for a
structure but allocates only for a pointer, so that to access structure’s members
through pointer bptr, we must allocate the memory using malloc() function.

• Now, individual structure members are accessed as:


bptr->name bptr->pages bptr->price

(*bptr).name (*bptr).pages (*bptr).price

• Here, -> is called arrow operator and there must be a pointer to the structure on the
left side of this operator.
32
struct book *bptr;

bptr=(struct book *) malloc(sizeof(struct book));

printf("\n Enter name:\t");

scanf("%s", bptr->name);
printf("\n Enter no. of pages:\t");
scanf("%d", &bptr->pages);
printf("\n Enter price:\t");
scanf("%f", & bptr->price=temp)

33
Pointer to Structure…
• Also, the address of a structure type variable can be
stored in a structure type pointer variable as follows:
struct book
{
char name[20];
int pages;
float price;
};
struct book b, *bptr;
bptr=&b;
• Here, the base address of b is assigned to bptr pointer.
34
Pointer to Structure…
• Now the members of the structure book can
be accessed in 3 ways as:
b.name bptr->name (*bptr).name
b.pages bptr->pages (*bptr).pages
b. price bptr-> price (*bptr).price

35
Pointer to array of structure
• Let we have a structure as follows:
struct book
{
char name[20];
int pages;
float price;
};
struct book b[10], *bptr;
• Then the assignment statement bptr=b; assigns
the address of the zeroth element of b to bptr.
36
Pointer to array of structure…
• The members of b[0] can be accessed as:
bptr->name bptr->pages bptr->price
• Similarly members of b[1] can be accessed as:
(bptr+1)->name (bptr+1)->pages (bptr+1)->price
• The following for statement can be used to print all the values
of array of structure b as:

for(bptr=b;bptr <b+10; bptr++)


printf("%s%d%f", bptr->name,bptr->pages, bptr->price);

37
Example program of structure with pointer
In this example, we are implementing a structure item, declaring structure pointer
pItem and by using pItem, we will assign and access the elements of the structure.
#include <stdio.h> /*read values using pointer*/
struct item printf("Enter product name: ");
{ gets(pItem->itemName);
char itemName[30]; printf("Enter price:");
int qty; scanf("%f",&pItem->price);
float price; printf("Enter quantity: ");
float amount; scanf("%d",&pItem->qty);
};
int main() /*calculate total amount of all quantity*/
{ pItem->amount =pItem->qty * pItem->price;
/*declare variable of structure item*/ /*print item details*/
struct item itm; printf("\nName: %s",pItem->itemName);
/*declare pointer of structure item*/ printf("\nPrice: %f",pItem->price);
struct item *pItem; printf("\nQuantity: %d",pItem->qty);
/*pointer assignment - assigning address of printf("\nTotal Amount: %f",pItem->amount);
itm to pItem*/ return 0;
pItem = &itm; }
38
Example program of structure with pointer

OUTPUT
Enter product name: computer
Enter price:34500
Enter quantity: 5

Name: computer
Price: 34500.000000
Quantity: 5
Total Amount: 172500.000000
--------------------------------

39
C program example of structure with pointer using
user define function

In this example, we have a structure named item with the pointer


structure object or variable named pItem,

Here we are implementing two user define functions


readItem() - to read structure members and
printItem() - to print the value of structure members.

40
#include <stdio.h> /*printItem() - to print values of item*/
struct item void printItem(struct item *i)
{ {
char itemName[30]; /*print item details*/
int qty; printf("\nName: %s",i->itemName);
float price; printf("\nPrice: %f",i->price);
float amount; printf("\nQuantity: %d",i->qty);
}; printf("\nTotal Amount: %f",i->amount);

/*readItem()- to read values of item and


calculate total amount*/ }
void readItem(struct item *i) int main()
{ {
/*read values using pointer*/ /*declare variable of structure item*/
printf("Enter product name: "); struct item itm;
gets(i->itemName); /*declare pointer of structure item*/
printf("Enter price:"); struct item *pItem;
scanf("%f",&i->price);
printf("Enter quantity: "); /*pointer assignment - assigning address of itm to
scanf("%d",&i->qty); pItem*/
pItem = &itm;
/*calculate total amount of all quantity*/ /*read item*/
i->amount = i->qty * i->price; readItem(pItem);
} /*print item*/
printItem(pItem);
return 0; 41
}
OUTPUT

Enter product name: PenDrive


Enter price:456
Enter quantity: 5

Name: PenDrive
Price: 456.000000
Quantity: 5
Total Amount: 2280.000000
--------------------------------

42
EXAMPLE: Accessing structure members using pointer

#include<stdio.h>
int main()
{ Output
struct my_structure NAME : Ram
{
NUMBER: 35
char name[20];
int number; RANK: 1
int rank;
};
struct my_structure variable = {"Ram",35,1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME: %s\n",ptr->name);
printf("NUMBER: %d\n",ptr->number);
printf("RANK: %d",ptr->rank);
return 0;
}
43
Self-referential structure in C

 A self-referential structure is a structure that can have members which point to


a structure variable of the same type.
 Self-referential structure is the concept in which one or more pointers pointing
to the same type of structure as their member.
 Widely used in dynamic data structures such as trees and linked lists
 It is a unique type of structure containing a member of its type. The member of
its type is a pointer variable of the same structure in which it has been declared.

44
Self-referential structure in C

Syntax:

struct structure_name
{
datatype datatype_name;
structure_name * pointer_name;
}

45
Self-referential structure in C

struct node
{
Example:
int data;
struct node *next;
};

Where ‘next’ is a pointer to a struct node variable, it should be remembered


that the pointer to the structure is similar to the pointer to any other variable.

Hence, a self-referential data structure is generally a structure definition that


includes at least one member that is a pointer to the structure of its kind.

46
Self-referential structure in C

typedef struct list


{
Example
void *data;
struct list *next;
}linked_list;

Here, in the above example, the list is self-referential structure as the *next is the
type struct list.

47
Self-referential structure in C
struct node
{  In this particular example, ‘link’ is a
int data; pointer to f type ‘node’ structure.
char value;  Hence, the structure ‘node’ is a self-
struct node * link; referential structure with ‘link’ as a
}; referencing pointer.
int main()  The pointer should be appropriately
{ initialized before accessing, as by default,
struct node object; it contains a garbage value.
return 0;
}

48
UNION
Union is also like structure, i.e. collection of different data types which are
grouped together. Each element in a union is called member.

 Union and structure in C are same in concepts, except allocating memory


for their members.
 Structure allocates storage space for all its members separately.
 Whereas, Union allocates one common storage space for all its members
 We can access only one member of union at a time. We can’t access all
member values at the same time in union.
 But, structure can access all member values at the same time. This is
because, Union allocates one common storage space for all its members.
Where as Structure allocates storage space for all its members separately.
 Many union variables can be created in a program and memory will be
allocated for each union variable separately.
49
Union
Union Data Type
1. A union is a user defined data type like structure.
2. The union groups logically related variables into a single
unit.
3. The union data type allocate the space equal to space
need to hold the largest data member of union.
4. The union allows different types of variable to share same
space in memory.
5. The method to declare, use and access the union is
same as structure except the keyword union.

50
Union
Example of Union

The union of Employee is declared as:

union employee
{
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int age;
}e; 51
Memory Space Allocation
8000
emp_id, dept_no, age
8002
salary
8004
name

8020

address

52
8050
Example
Declare a union, initializing and accessing the members of the union.
Using normal variable Using pointer variable
Syntax: Syntax:
union tag_name union tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
Example: Example:
union student union student
{ {
int mark; int mark;
char name[10]; char name[10];
float average; float average;
}; };
Declaring union using normal variable: Declaring union using pointer variable:
union student report; union student *report, rep;
Initializing union using pointer variable:
Initializing union using normal variable:
union student rep = {100, “Manish”, 99.5};
union student report = {100, “Manish”, 99.5};
report = &rep;
Accessing union members using normal variable: Accessing union members using pointer variable:
report.mark; report -> mark;
report.name; report -> name;
report.average; report -> average;
53
Example program for C union:

#include <stdio.h>
#include <string.h> // assigning values to record2 union variable
union student printf("Union record2 values example\n");
{ strcpy(record2.name, "Manish");
char name[20]; printf(" Name: %s \n", record2.name);
strcpy(record2.subject, "Physics");
char subject[20];
printf(" Subject: %s \n", record2.subject);
float percentage; record2.percentage = 99.50;
}; printf(" Percentage : %f \n", record2.percentage);
int main() return 0;
{ }
union student record1;
union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Ramesh");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name:%s\n", record1.name);
printf(" Subject:%s\n",record1.subject);
printf(" Percentage :%f \n\n",
record1.percentage);
54
Example program for C union:

Output

Union record1 values example


Name:
Subject:
Percentage :86.500000

Union record2 values example


Name: Manish
Subject: Physics
Percentage : 99.500000

55
Example program for C union:
Explanation for above C union program:
There are 2 union variables declared in this program to understand the difference in
accessing values of union members.
Record1 union variable:
“Ramesh” is assigned to union member “record1.name” . The memory location name is
“record1.name” and the value stored in this location is “Ramesh”.
Then, “Maths” is assigned to union member “record1.subject”. Now, memory location
name is changed to “record1.subject” with the value “Maths” (Union can hold only one
member at a time).
Then, “86.50” is assigned to union member “record1.percentage”. Now, memory location
name is changed to “record1.percentage” with value “86.50”.
Like this, name and value of union member is replaced every time on the common storage
space.
So, we can always access only one union member for which value is assigned at last. We
can’t access other member values.
So, only “record1.percentage” value is displayed in output. “record1.name” and
“record1.percentage” are empty. 56
Example program for C union:

Record2 union variable:

If we want to access all member values using union, we have to access the
member before assigning values to other members as shown in record2 union
variable in this program.
Each union members are accessed in record2 example immediately after
assigning values to them.

If we don’t access them before assigning values to other member, member


name and value will be over written by other member as all members are using
same memory.
We can’t access all members in union at same time but structure can do that.

57
Example program for C union:

#include <stdio.h>
#include <string.h> // assigning values to record2 union variable
union student printf("Union record2 values example\n");
{ strcpy(record2.name, "Manish");
char name[20]; printf(" Name: %s \n", record2.name);
char subject[20]; strcpy(record2.subject, "Physics");
float percentage; printf(" Subject: %s \n", record2.subject);
}; record2.percentage = 99.50;
int main() printf(" Percentage : %f \n", record2.percentage);
{ return 0;
union student record1; }
union student record2;

// assigning values to record1 union variable


printf("Union record1 values example\n");
strcpy(record1.name, "Ramesh");
printf(" Name:%s\n", record1.name);
strcpy(record1.subject, "Maths");
printf(" Subject:%s\n",record1.subject);
record1.percentage = 86.50;
printf(" Percentage :%f \n\n", record1.percentage);

58
Example program for C union:

OUTPUT

Union record1 values example


Name:Ramesh
Subject:Maths
Percentage :86.500000

Union record2 values example


Name: Manish
Subject: Physics
Percentage : 99.500000

59
Difference between structure and union in C:
Structure Union
Union allocates one common storage space for
all its members.
Structure allocates storage space for all its
Union finds that which of its member needs
members separately.
high storage space over other members and
allocates that much space
Union occupies lower memory space over
Structure occupies higher memory space.
structure.
We can access all members of structure at a We can access only one member of union at a
time. time.
Structure example: Union example:
struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };
For above structure, memory allocation will For above union, only 8 bytes of memory will
be like below. be allocated since double data type will
int mark – 2B (32-bit system) occupy maximum space of memory over other
char name[6] – 6B data types.
double average – 8B
Total memory allocation = 2+6+8 = 16 Bytes Total memory allocation = 8 Bytes
60

You might also like