0% found this document useful (0 votes)
4 views17 pages

C Module 5

The document covers key concepts in C programming related to structures, unions, enumerations, and typedefs. It explains how to define and use structures, including memory allocation, member access, and passing structures to functions. Additionally, it discusses unions, bit-fields, enumerations, and the use of sizeof for portability, along with the typedef keyword for creating data type aliases.
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)
4 views17 pages

C Module 5

The document covers key concepts in C programming related to structures, unions, enumerations, and typedefs. It explains how to define and use structures, including memory allocation, member access, and passing structures to functions. Additionally, it discusses unions, bit-fields, enumerations, and the use of sizeof for portability, along with the typedef keyword for creating data type aliases.
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

PROGRAMMING IN C

B.E – II SEMESTER SUB CODE: 1BEIT205

Module- 5

Structures, Unions, Enumerations, and typedef: Structures, Arrays of Structures, Passing


Structure to Functions, Structure Pointers, Arrays and Structures within Structures, Unions,
Bit-Fields, Enumerations, Using sizeof to Ensure Portability, typedef.

Textbook 1: Chapter 7

Chapter – 1
STRUCTURES:
Structure: A structure is a convenient tool for handling a group of logically related data items. like it can
be used to represent a set of attributes such as student name, roll number and marks. Structure helps to
organize complex data in a more meaningful way.
Examples of such structure are;
Time: seconds, minutes, hours
Date: day, month, year
Book: author, title, price, year
City: name, country, population
Definition of Structure: Structure is a collection of one or more variables to hold the data values of the
same type or different types. The data items in the structure are called the members of the structure.
General Syntax for Defining a structure or Syntax for Declaring the structure.

struct → is a keyword, introduces the structure definition


● structure_name → is the name given to the structure or tag
● data_type1, data_type2………data_type n → are basic data types
● member_name 1, member_name 2………member_name n are data items or structure variables.
● The declaration of the structure members are enclosed in braces
● The data items in the structure are called the members of the structure.
● The structure variable declaration is similar to the declaration of variables of any other data types.
● A semicolon follows the closing brace, terminating the entire structure.

Example 1 ; A structure to hold employee information


struct employee
{
int id_no;
char name[15];
char designation[10];
float salary;
};
Explanation:
The struct keyword is followed by structure name as employee
It contains four members, an integer named id no, character named as name[15] which is an array,
character named as designation[15] which is an array and float named as salary.
Memory Allocation for structure employee

id_no name Designation salary


2 bytes 15 bytes 10 bytes 4 bytes

Total = 31 bytes of structure employee.

Example 2
structure to hold student information struct
student
{
int reg_no;
char name[15];
char branch[10];
int semester; float
total_marks;
};
Explanation:
● The struct keyword is followed by structure name as student
● It contains five members, an integer named reg_no, character named as name[15] which is an
array, character named as branch[15] which is an array, integer named by semester and float
named as total marks.
Memory Allocation for structure employee

reg_no name branch semester total_marks


2 bytes 15 bytes 10 bytes 2 bytes 4 bytes

Total = 33 bytes of struct student.

General Syntax for Declaring the structure Variables.

structure_type → is the type of a structure. It takes the keyword struct followed by the name of the
structure.
It is derived data type
varlist → one or more variables separated by commas.
In the above example 1, a struct employee is one structure having four fields. Now struct employee is a
base type for the structure. Therefore all such structures can be declared by writing, struct employee
emp1,emp2,emp3;
Here, emp1, emp2 and emp3 are structure variables each having four fields. This statement must be
written after the structure definition as shown below;

Example 1 ; A structure to hold employee information can be rewritten as;

emp1, emp2 & emp3 are written between the closing brace and the semicolon.

Accessing structure members


● As we know that structure variables reserve memory space for its members, the structure
members can be accessed to store or retrieve data values.
● Thus a member of structure can be accessed by using period (.) or dot operator. The real
name of the dot operator is member access operator.
Syntax for Accessing structure members

structure_variable_name → structure variables ( . ) → period or dot operator member_name →


structure members
Example 1: Program to input and display the information of student
Structure members initialization
● Like initialization of array elements, structure members can be initialized. This initialization
is made in the declaration part of a C program.
● The initialization of each structure member can be done if the storage class is either extern
or static.
Example 1:
Copying and Comparing Structures variable in C:

In C, you can copy structure variables using the assignment operator ( =) . Comparing structure
variables directly == is not allowed; you must compare them member by member, typically within a
with custom
function.
Copying Structure Variables

 Assignment Operator: This is the simplest and most common method. The compiler handles the
member-by-member copy.

Example 1:

#include <stdio.h>

#include <string.h>

struct Point

int x;

int y;

};

int main() {

struct Point p1 = {10, 20};

struct Point p2;

// Copy p1 to p2 p2

= p1;

printf("p2.x: %d, p2.y: %d\n", p2.x, p2.y);

return 0;

Output:
p2.x: 10, p2.y: 20

Comparing Structure Variables


Direct comparison using == or !=operators is not valid for structure variables in C. The C
standard does not guarantee that padding bytes within a structure will have consistent values, which would
cause a byte-wise comparison to fail unpredictably even if all members are identical.

The standard approach is to write a custom function that compares members individually:
Example 1:
#include <stdio.h> #include
<string.h>
#include <stdbool.h> // For boolean type, available since C99 struct
Point {
int x;
int y;

};
// Function to compare two Point structures
bool arePointsEqual(struct Point p1, struct Point p2) { if (p1.x
== p2.x && p1.y == p2.y) {
return true;
}
return false;
}
int main() {
struct Point p1 = {10, 20};
struct Point p2 = {10, 20};
struct Point p3 = {30, 40};
if (arePointsEqual(p1, p2)) { printf("p1
and p2 are equal\n");

} else {
printf("p1 and p2 are different\n");
}

if (arePointsEqual(p1, p3)) { printf("p1


and p3 are equal\n");

} else {
printf("p1 and p3 are different\n");
}
return 0;
}
Output:
p1 and p2 are equal
p1 and p3 are different

Passing Structure to Functions:

In C we can pass a structure to a function using three distinct methods: passing individual members, passing the
entire structure by value, or passing the structure by reference/pointer.

1. Passing Individual Members


You pass only specific fields of the structure using the dot (.) operator. The function treats them as ordinary
variables.

#include <stdio.h>
struct Student
{
char name[20];
int age;
};
void printAge(int age) {
printf("Age: %d\n", age);
}
int main() {
struct Student s1 = {"Raju", 20};
printAge([Link]); // Passing individual member
return 0;

2. Passing Entire Structure by Value


The entire structure is copied into the function's memory space. Changes made inside the function do not affect
the original structure.

#include <stdio.h>
struct Point
{
int x;
int y;
};

void movePoint(struct Point p)


{
p.x += 10; // Only modifies the local copy
printf("Inside function: (%d, %d)\n", p.x, p.y);
}

int main() {
struct Point p1 = {5, 5};
movePoint(p1);
printf("Inside main: (%d, %d)\n", p1.x, p1.y);
return 0;
}
Structure Pointers in C:

A structure pointer is a pointer that stores the address of a structure variable. It allows you to access and modify

structure members efficiently without copying the entire structure.

Declaration:

struct Student {
int id;
char name[20];
};

struct Student s1;


struct Student *ptr;

Here, ptr is a pointer to a struct Student.

Assigning a Structure Address


ptr = &s1;

Now ptr points to the structure variable s1.

Accessing Members Using a Structure Pointer

There are two ways:

1. Using Dereference Operator (*)


(*ptr).id = 101;

The parentheses are necessary because. has higher precedence than *.

2. Using Arrow Operator (->)


ptr->id = 101;

This is equivalent to (*ptr).id and is more commonly used.


Example:

#include <stdio.h>

struct Student {

int id;

char name[20];

};

int main() {

struct Student s1 = {101, "Raju"};

struct Student *ptr = &s1;

printf("ID: %d\n", ptr->id);

printf("Name: %s\n", ptr->name);

return 0;

Output:

ID: 101
Name: Raju

Array of Structure:
we can declare an array of structures, each element of the array representing a structure variable.

In the above example, struct marks have three data items or three structure variables student[0], student[1]
and student[3] whose values are initialized.

student[0].subject1=45; student[1].subject1=75; student[2].subject1=57;


student[0].subject2=68; student[1].subject2=53; student[2].subject2=36;
student[0].subject3=81; student[1].subject3=69; student[2].subject3=71;
Array within Structure
C permits the use of arrays as structure members. We can use single dimensional or multidimensional
arrays.
Example 1 ; A structure to hold student information
struct marks
{
int reg_no;
float subject[3];
};
struct marks student[2];
Explanation:
● In the above example, the structure marks contains two members.
● First is an integer named reg_no and second is floating point named subject which is an array
containing three elements such as subject[0], subject[1] and subject[2].
● The struct marks also contain two variables which are student[1] and student[2] which is also
an array.
UNION:

A union in C is a user-defined data type that allows you to store different data types in the same memory
location. While it looks almost identical to a struct in its syntax, a union allocates only enough memory to
hold its largest member, meaning you can only store and access one member's value at a time.

A union is a user-defined data type in C that allows different data members to share the same memory

location. Unlike a structure, all members of a union use the same storage space.

Syntax
union Data {
int i;
float f;
char str[20];
};

Example:
#include <stdio.h>
union Data {
int i;
float f;
};
int main() {
union Data d;
d.i = 10;
printf("i = %d\n", d.i);
d.f = 5.5;
printf("f = %.1f\n", d.f);
return 0;
}

Output:
i=10
f=5.5

Key Differences: Struct vs. Union


Feature struct union

Memory Every member gets its own unique All members share the same starting
Allocation memory address. memory address.

Sum of all member sizes (plus compiler Equal to the size of the largest
Total Size
padding). member.

All member values can be used Only the most recently assigned
Data Access
simultaneously. member is valid.
Bit-Fields in C:

Bit-fields allow you to allocate a specific number of bits to structure or union members, helping save memory
when storing small values.

Syntax
struct Flags {
unsigned int a : 1;
unsigned int b : 2;
unsigned int c : 3;
};

Here:

 a uses 1 bit
 b uses 2 bits
 c uses 3 bits

Bit-Fields in a Union

A union can contain a bit-field structure to access individual bits and the whole data using the same memory.

#include <stdio.h>

union Data {
struct {
unsigned int a : 1;
unsigned int b : 2;
unsigned int c : 3;
} bits;
unsigned int value;
};
int main() {
union Data d;

[Link] = 15; // Binary: 1111

printf("a = %u\n", [Link].a);


printf("b = %u\n", [Link].b);
printf("c = %u\n", [Link].c);

return 0;
}

ENUMERATION:

In C programming, an enumeration (or enum) is a user-defined data type consisting of named integer
constants. Enums replace hardcoded magic numbers with descriptive words, drastically improving code
readability and maintainability.

Syntax and Core Concepts


To define an enum, use the enum keyword followed by the name of the enumeration type and a list of elements
separated by commas.
Example:

#include <stdio.h>
// 1. Defining the enum type
enum Level {
LOW, // Automatically assigned 0
MEDIUM, // Automatically assigned 1
HIGH // Automatically assigned 2
};
int main() {
// 2. Declaring an enum variable
enum Level current_status = MEDIUM;

// 3. Using the enum variable


if (current_status == MEDIUM) {
printf("The status is Medium. Integer value: %d\n", current_status);
}
return 0;
}

Output:
The status is Medium. Integer value: 1

Using sizeof to Ensure Portability:

Using sizeof to Ensure Portability in C – Short Notes

The sizeof operator returns the size (in bytes) of a data type or variable. Using sizeof makes programs portable
because data type sizes may vary across different systems and compilers.

Syntax
sizeof(data_type)
sizeof(variable)

Example:
#include <stdio.h>

int main()
{
printf("Size of int = %zu bytes\n", sizeof(int));
printf("Size of float = %zu bytes\n", sizeof(float));
return 0;
}

Output:
Size of int = 4 bytes
Size of float = 4 bytes
typedef:

The typedef keyword is used to create a new name (alias) for an existing data type. It improves code readability
and makes complex declarations easier to understand.

Syntax
typedef existing_data_type new_name;

Example:
#include <stdio.h>
typedef int Integer;
int main() {
Integer num = 10;
printf("%d", num);
return 0;
}

Output:
10

Using typedef with Structures

Without typedef:

struct Student {
int id;
};
struct Student s1;

With typedef:

typedef struct {
int id;
} Student;

Student s1;

Advantages

 Makes code shorter and easier to read.


 Simplifies complex declarations (e.g., pointers, structures).
 Improves portability and maintainability.
 Provides meaningful names for data types.

You might also like