module 4
module 4
Structures and
Unions in C
What will you learn?
Structures
Unions
Structures versus Unions
WHY STRUCTURES?
Structures are used to group different types of data
together under a single name. (e.g., representing a person's
information such as age, name, and salary).
Memory Management
struct book_bank
struct tag_name
{
{
char title[25];
data type member 1;
char author[20];
data type member 2;
int pages;
data type member 3;
float price;
...
};
data type member n;
};
DECLARING STRUCTURE
VARIABLES
After defining the structure, we declare variables of the
structure data type. A structure variable declaration is similar to
that of an ordinary variable declaration.
Example: -
Eg:
struct employee
int empno;
char name[20];
float salary;
};
MEMORY
REPRESENTATION
E 145 Ajay Kumar 15000
Copying structures
Array of structures
Pointer to structures
ACCESSING STRUCTURE ELEMENTS
Members/elements of the structure are accessed using an operator
“.” which is known as member access operator or direct
selection operator.
struct book_bank
{
char title[25];
char author[20];
int pages;
float price;
} book1;
data-type
member1;
member2; {
int m;
……………………….. float x;
data-type char c;
memberN; };
};
DECLARING UNION
VARIABLES
Below is the syntax for declaring the union
union <union_name ><variable-name>;
Ex:
Union:-
union item
{
int m;
float x;
char c;
};
Union variable:- union item code;
MEMORY
REPRESENTATION
union item
{
int m;
float x;
char c;
};
65497 65498 65499 65500
c
EXAMPLE PROGRAM FOR
UNIONS:
#include <stdio.h>
// Define a union
union Data {
int i;
float f;
char str[20];
};
int main() {
// Create a union variable
union Data data;
// Assign an integer value
data.i = 10;
printf("data.i : %d\n", data.i);
// Assign a float value (this overwrites the integer value)
data.f = 220.5;
printf("data.f : %.1f\n", data.f);
// Assign a string (this overwrites the float value)
strcpy(data.str, "C Programming");
printf("data.str : %s\n", data.str);
return 0;
}
STRUCTURES
VERSUS
UNIONS
Difference Structure Union