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

Structure and union

The document provides an overview of structures and unions in C programming, covering topics such as defining structures, initializing variables, accessing members, and the differences between structures and unions. It includes examples of nested structures, pointers to structures, and how to pass structures to functions. Additionally, it discusses the memory allocation differences between structures and unions and provides exercises for practical understanding.

Uploaded by

23ec043
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)
16 views

Structure and union

The document provides an overview of structures and unions in C programming, covering topics such as defining structures, initializing variables, accessing members, and the differences between structures and unions. It includes examples of nested structures, pointers to structures, and how to pass structures to functions. Additionally, it discusses the memory allocation differences between structures and unions and provides exercises for practical understanding.

Uploaded by

23ec043
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/ 46

EC104: Applied Programming

Unit 1: Structure and Union


Topics
• Defining a Structure, Declaring Structure Variables
• Initialization Of Structure Variables, Accessing Members of a
Structure, Assignment of Structure Variables
• Storage of Structures in Memory, Size of Structure
• Array of Structures, Arrays Within Structures, Nested Structures
• Pointers to Structures, Pointers Within Structures, Structures And
Functions
• Definition of Union, Difference Between Structure and Union
Defining a Structure
struct name_of_structure
{ Name of structure or structure tag
Keyword
char title[20];
char author[20];
int pages; Data fields also called as structure elements
float price; or members

};
General format of Structure
struct tag_name
{
data type member1;
data type member2;
data type member2;
------------ ------------
};
Declaring structure variables

• Method 1: Like basic declaration of variables


struct struct_name variable1, variable2, variable3;

• Method 2: During declaration of structure(with structure)


Struct struct_name
{ datatype member1;
datatype member2;
----------------- -----------
} variable1, variable2, variable3;
Lets do practice
1. Create a structure called Library to hold accession number, title of
the book, author name, price of the book and flag indicating whether
the book is issued or not.
2. Create a structure called Result for students. Structure will have
members like roll number, marks for three subjects and total of three
subjects.
3. Create a structure called Emp_Details which contains members like
name of employee, designation, department name, basic pay.
Initialization of structure variables
• Structure members cannot be initialized with declaration.

• For example the following C program fails in compilation.


struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
• The reason for above error is simple, when a datatype is declared, no
memory is allocated for it.
• Memory is allocated only when variables are created.
• Structure members can be initialized using curly braces ‘{}’.

struct Point
A valid initialization.
{
Member x gets value 0
int x, y;
and y gets value 1.
};
The order of declaration
int main()
is followed.
{
struct Point p1 = {0, 1};
}
Type defined structures
• We can also use keyword typedef to define a structure as follows:

typedef struct
{
type member1;
type member2;
}
Variables defining methods:
#include<stdio.h> #include<stdio.h>
struct Point{
typedef struct Point{
int x; int x;
int y;
}; int y;
} Point;
int main() {
struct Point p1; int main()
{
p1.x = 1;
Point p1;
p1.y = 3; p1.x = 1;
printf("%d \n", p1.x); p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
printf("%d \n", p1.y);
return 0; return 0;
} }
Accessing Structure Members
• The members themselves are not
#include<stdio.h>
variables.
struct Point{
• They should be linked to the
int x;
structure variables in order to make
int y;
them meaningful members.
};
• The link between a member and a
int main() {
variable is established using the
struct Point p1;
member operator ‘.’
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}
Rules for Initializing for structures
• We cannot initialize individual members inside the structure
template.
• The order of values enclosed in braces must match the order of
members in the structure definition.
• It is permitted to have a partial initialization. We can initialize only
first few members and leave the remaining blank. The uninitialized
members should be only at the end of the list.
• The uninitialized members will be assigned default values as follows:
• Zero for integer and floating point numbers.
• ‘\0’ for characters and strings.
Copying and comparing structure variables
• Two variables of same structure type can be copied the same way as
ordinary variables.
• If p1 and p2 belong to the same structure, then p1=p2;
p2=p1; are valid

C does not permits any logical operations on structure variables.


Exercise 1:
• Define a structure that describes a student having members Roll_no,
Name, Mark1, Mark2, Mark3. Write a program for five students to
print the total marks and average of marks for each student.
ARRAYAS MEMBER OF STRUCTURE

• Let’s create structure called student to store name, roll no and marks of 5 subjects.

struct student
{
char name[20];
int roll_no;
float marks[5];
}std1;

std1.marks[0] – refers to the marks in the first subject


std1.marks[1] – refers to the marks in the second subject
ARRAY OF STRUCTURE VARIABLE

• Like other primitive data types, we can create an array of structures.


struct student
{
char name[20];
int roll_no;
float marks[5];
}std[5];

std[0].marks[0] – refers to the marks of first student in the first subject


std[1].marks[2] – refers to the marks of the second student in the third subject
OUTPUT
EXAMPLE

#include<stdio.h> for(i = 0; i < MAX; i++ )


#include<string.h> {
#define MAX 2 printf("\nEnter details of student %d\n\n", i+1);
#define SUBJECTS 2
printf("Enter name: ");
struct student scanf("%s", std[i].name);
{
char name[20]; printf("Enter roll no: ");
int roll_no; scanf("%d", &std[i].roll_no);
float marks[SUBJECTS];
}; for(j = 0; j < SUBJECTS; j++)
{
int main() printf("Enter marks: ");
{ scanf("%f", &std[i].marks[j]);
struct student std[MAX]; }
int i, j; }
float sum = 0;
printf("\n");

printf("Name\tRoll no\tAverage\n\n");

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


{
sum = 0;

for(j = 0; j < SUBJECTS; j++)


{
sum += std[i].marks[j];
}
printf("%s\t%d\t%.2f\n",std[i].name, std[i].roll_no, sum/SUBJECTS);
}
return 0;
}
SIZE OF STRUCTURE
#include<stdio.h>

struct student
{
char name[20]; //1 Byte each = 20 Bytes
int roll_no; //4 Bytes Question:
float marks[2]; //4 Byte each = 8 Bytes How do we get the size of the
}; structure?

int main() Answer:


{ • By adding the size of all elements of
struct student std[2]; the structure.
• std[0] and std[1] will each get 32
printf("\nstructure size : %d Bytes\n",sizeof(struct student));
return 0; Bytes of memory.
}
LET’S PRACTICE

struct Student struct Person struct Address


{ { {
int id; char name[40]; char name[50];
char name[20]; int citNo; char street[100];
float percentage; float salary; char city[50];
}; }; char state[20];
int pin;
};
NESTED STRUCTURE OR STRUCTURE
WITHIN STRUCTURE

• 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.
• The structure can be nested in the following ways.
• By Separate structure
• By Embedded structure
1. SEPARATE STRUCTURE

• Here, we create two structures, but the struct Date


{
dependent structure should be used inside the
int dd;
main structure as a member. int mm;
int yyyy;
• As you can see, doj (date of joining) is the
};
variable of type Date. Here doj is used as a
member in Employee structure. struct Employee
{
• In this way, we can use Date structure in int id;
many structures. char name[20];
struct Date doj;// Date structure variable
}emp1; // Employee structure variable
2. EMBEDDED STRUCTURE
struct Employee
{
• The embedded structure enables us to declare int id;
the structure inside the structure. char name[20];
• Hence, it requires less line of codes but it can struct Date
not be used in multiple data structures. {
int dd;
int mm;
int yyyy;
}doj; // Date structure variable
}emp1; // Employee structure variable
ACCESSING NESTED STRUCTURE

• We can access the member of the nested structure by… For Example:

Outer_structure.Nested_structure.Member
emp1.doj.dd;
emp1.doj.mm;
emp1.doj.yyyy;
Pointers to Structure
• 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.
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> s1.batch = 2023;
#include <string.h>
printf("Roll Number: %d\n", (*ptr).roll_no);
struct Student {
int roll_no; printf("Name: %s\n", (*ptr).name);
char name[30];
char branch[40]; printf("Branch: %s\n", (*ptr).branch);
int batch;
}; printf("Batch: %d", (*ptr).batch);
int main() return 0;
{ }
struct Student s1;
struct Student* ptr = &s1;

s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
// C Program to demonstrate Structure pointer ptr = &s;
// Taking inputs
printf("Enter the Roll Number of Student\n");
#include <stdio.h> scanf("%d", &ptr->roll_no);
#include <string.h> printf("Enter Name of Student\n");
scanf("%s", &ptr->name);
// Creating Structure Student printf("Enter Branch of Student\n");
struct Student { scanf("%s", &ptr->branch);
int roll_no; printf("Enter batch of Student\n");
char name[30]; scanf("%d", &ptr->batch);
char branch[40];
int batch; // Displaying details of the student
}; printf("\nStudent details are: \n");
printf("Roll No: %d\n", ptr->roll_no);
// variable of structure with pointer defined printf("Name: %s\n", ptr->name);
printf("Branch: %s\n", ptr->branch);
struct Student s, *ptr; printf("Batch: %d\n", ptr->batch);

int main() return 0;


{ }
PASSING STRUCTURE TO A FUNCTION

• A structure can be passed to any function from main function or from any sub function.
• If structure is defined within the function only then it won’t be available to other functions unless
it is passed to those functions by value or by address.
• Else, we have to declare structure variable as global variable. That means, structure variable
should be declared outside the main function. So, this structure will be visible to all the functions
in a C program.
• It can be done in below ways.
EXAMPLE
#include <stdio.h> record.id=1;
#include <string.h> strcpy(record.name, "Raju");
record.percentage = 86.5;
struct student
{ func(record);
int id; return 0;
char name[20]; }
float percentage;
}; void func(struct student record)
{
void func(struct student record); printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
int main() printf(" Percentage is: %f \n", record.percentage);
{ }
struct student record;
EXAMPLE
#include <stdio.h> record.id=1;
#include <string.h> strcpy(record.name, "Raju");
record.percentage = 86.5;
struct student
{ func(&record);
int id; return 0;
char name[20]; }
float percentage;
}; void func(struct student *record)
{
void func(struct student *record); printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
int main() printf(" Percentage is: %f \n", record->percentage);
{ }
struct student record;
UNION
• A union is a special data type available in C that allows storing 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.
• Unions provide an efficient way of using the same memory location for multiple
purposes.
• Defining a Union: To define a union, you must use the union statement in the
same way as you did while defining a structure. The union statement defines a
new data type with more than one member for your program.
UNION
SYNTAX
union keyword

union union_name
{
//Members / Fields of Union
}union_var; semicolon
STRUCTURE VS UNION IN C
structure union
Keyword “struct” is used to define the structure. “union” is used to define union.

Size When a variable is associated with the When a variable is associated with the union,
structure, compiler allocates memory for each compiler allocates memory by considering
member. the size of the largest member.
The size of structure is greater than or equal The size of union is the size of the largest
to the sum of the sizes of it’s members. member.
Memory Each member is assigned a unique storage Memory allocated is shared by individual
location. members.
Value altering Altering value of a member will not affect Altering value of a member will affect value
other members. of other members.
Accessing Individual members can be accessed at a Only one member can be accessed at a time.
members time.
Initialization Many members of a structure can be Only the first member of a union can be
of members initialized at a time. initialized.
Example of Restrictions

#include<stdio.h>

union Address
{
char name[50];
char street[100];
};

int main()
{
union Address std = {"dipsi", "75th Street"};

printf("\nname: %s",std.name);
printf("\nstreet: %s",std.street);
printf("\n");
return 0;
}
SIMILARITIES BETWEEN STRUCTURE
AND UNION

• Both are user-defined data types used to store data of different types as a single unit.
• 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.
• ‘.’Operator is used for accessing members.
SIZE OF UNION
#include<stdio.h>

union student
{
char name[20]; //1 Byte each = 20 Bytes
int roll_no; //4 Bytes Question:
float marks[2]; //4 Byte each = 8 Bytes How do we get the size of the union?
};
Answer:
int main() • By size of the largest member.
{
union student std[2];

printf("\n union size : %d Bytes\n",sizeof(union student));


return 0;
}
LET’S PRACTICE

union Student union Person union Address


{ { {
int id; char name[40]; char name[50];
char name[20]; int citNo; char street[100];
float percentage; float salary; char city[50];
}; }; char state[20];
int pin;
};

You might also like