0% found this document useful (0 votes)
19 views16 pages

Unit 4 Part 1

This document provides an introduction to structures and unions in C programming, explaining their definitions, syntax, and usage. It covers key concepts such as accessing structure members, initializing structures, nested structures, arrays of structures, and pointers to structures, along with examples. Additionally, it discusses the differences between structures and unions, highlighting their memory allocation and use cases.
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)
19 views16 pages

Unit 4 Part 1

This document provides an introduction to structures and unions in C programming, explaining their definitions, syntax, and usage. It covers key concepts such as accessing structure members, initializing structures, nested structures, arrays of structures, and pointers to structures, along with examples. Additionally, it discusses the differences between structures and unions, highlighting their memory allocation and use cases.
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/ 16

K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

INTRODUCTION TO PROGRAMMING
UNIT – 4 PART – 1
Structures and Unions:

Structures, Accessing elements of a structure, Array of structures; pointer to


structure; Unions, Compare structures and unions; Bit fields;

What is a Structure in C?

A structure in C is a user-defined data type that aggregates different types of


variables into a single entity. It allows grouping of related information, making
it easier to organize and manipulate complex data.

For example, if we need to store information about an employee, we may want


to group their ID, name, and salary into a single unit. A structure makes this
possible by associating these variables under a single name.

Features of a Structure

1. Heterogeneous Data: Structures can store variables of different data


types together.
2. Memory Management: Each member of the structure occupies its own
memory space.
3. Modularity: Structures help create modular and organized programs.
4. Reusability: Once defined, a structure can be reused across the
program.

Syntax of a Structure

The syntax for defining and declaring a structure is as follows:

struct StructureName {
data_type member1; // Member 1 declaration
data_type member2; // Member 2 declaration
// Add more members as needed
};

 struct: A keyword used to declare a structure.


 StructureName: The identifier for the structure.
 data_type member1, member2, ...: Variables (also called "members") of
different data types.
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

Example Syntax
struct Employee {
int id; // Integer variable to store employee ID
char name[50]; // Character array to store employee name
float salary; // Float variable to store employee salary
};

Declaration of Structure Variables

Once a structure is defined, you can declare variables of that structure type.
There are two ways:

1. Separate Declaration: Declare the structure first, then create variables.


2. Inline Declaration: Declare variables at the time of structure definition.

1. Separately after defining the structure:

struct Employee emp1, emp2;

2. At the time of structure definition:

struct Employee {
int id;
char name[50];
float salary;
} emp1, emp2;

Initializing Structure Elements

Structure variables can be initialized at the time of declaration or later in the


program.

Direct Initialization

struct Employee emp1 = {101, "Alice", 75000.0};

Here:

 id is initialized to 101.
 name is initialized to "Alice".
 salary is initialized to 75000.0.

Partial Initialization

struct Employee emp2 = {102, "Bob"};


K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

 id is initialized to 102.
 name is initialized to "Bob".
 salary is initialized to 0.0 (default value for float).

Accessing Structure Members

To access or modify the members of a structure, use the dot operator (.) with
the structure variable.

Example:
#include <stdio.h>
struct Employee {
int id;
char name[50];
float salary;
};

int main() {
struct Employee emp1; // Declare a structure variable

// Assign values to members


emp1.id = 101;
snprintf(emp1.name, sizeof(emp1.name), "John Doe");
emp1.salary = 75000.50;

// Access and print structure members


printf("Employee Details:\n");
printf("ID: %d\n", emp1.id);
printf("Name: %s\n", emp1.name);
printf("Salary: %.2f\n", emp1.salary);

return 0;
}

Output:
Employee Details:
ID: 101
Name: John Doe
Salary: 75000.50

Important Notes about Structures

 Memory Allocation: Each member has its own memory location, and
the size of the structure is the sum of all its members (plus potential
padding for alignment).
 Initialization: Structure members can be initialized at the time of
declaration:
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

struct Employee emp1 = {101, "John Doe", 75000.50};

 Nested Structures: Structures can contain other structures as


members, enabling hierarchical data organization.

Advantages of Structures

 Simplifies the management of related data.


 Increases code readability and maintainability.
 Facilitates modeling real-world entities in programming.

Real-World Applications

 Representing records (e.g., students, employees, products).


 Storing complex data (e.g., coordinates, RGB values).
 Used in database management systems (DBMS) for managing large
amounts of data

Nested Structures in C

A nested structure is a structure within another structure. This allows


creating complex data types where one structure can act as a member of
another structure. Nested structures are helpful in modeling hierarchical or
composite data.

Syntax of Nested Structures


struct OuterStructure {
struct InnerStructure {
data_type member1;
data_type member2;
} innerVar; // Inner structure variable as a member of the outer structure

data_type outerMember;
};

Explanation

 OuterStructure: The primary structure that contains one or more


instances of another structure.
 InnerStructure: The structure that is nested within the outer structure.

Example 1: Employee with Address


#include <stdio.h>

// Nested Structures
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

struct Address {
char city[50];
int zipCode;
};

struct Employee {
int id;
char name[50];
struct Address address; // Nested structure as a member
};

int main() {
struct Employee emp = {101, "John Doe", {"New York", 10001}};

// Accessing members of the nested structure


printf("Employee Details:\n");
printf("ID: %d\n", emp.id);
printf("Name: %s\n", emp.name);
printf("City: %s\n", emp.address.city);
printf("ZIP Code: %d\n", emp.address.zipCode);

return 0;
}

Output:

Employee Details:
ID: 101
Name: John Doe
City: New York
ZIP Code: 10001

Accessing Nested Structure Members

To access members of a nested structure:

1. Use the dot operator (.) with the outer structure variable for direct
access.
2. If using a pointer to a structure, use the arrow operator (->).

Example : Student with Marks

#include <stdio.h>

// Nested Structures
struct Marks {
int math;
int science;
int english;
};
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

struct Student {
int rollNumber;
char name[50];
struct Marks marks; // Nested structure as a member
};

int main() {
struct Student student1 = {1, "Bob", {85, 90, 78}};

printf("Student Details:\n");
printf("Roll Number: %d\n", student1.rollNumber);
printf("Name: %s\n", student1.name);
printf("Marks:\n");
printf(" Math: %d\n", student1.marks.math);
printf(" Science: %d\n", student1.marks.science);
printf(" English: %d\n", student1.marks.english);

return 0;
}
Output:
Student Details:
Roll Number: 1
Name: Bob
Marks:
Math: 85
Science: 90
English: 78

Array of Structures

An array of structures is a collection of structure variables that are stored in


contiguous memory locations. It is used to manage multiple records of the
same type efficiently.

Key Points

1. Each element of the array is a separate structure variable.


2. The array elements can be accessed using the index and the dot operator (.) to
access individual members.
3. Useful for scenarios like managing data for multiple employees, students,
products, etc.

Syntax
struct StructureName {
data_type member1;
data_type member2;
// Additional members
};
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

struct StructureName arrayName[array_size];

Example with Explanation


#include <stdio.h>

// Define a structure
struct Employee {
int id; // Employee ID
char name[50]; // Employee name
float salary; // Employee salary
};

int main() {
// Declare and initialize an array of structures
struct Employee emp[3] = {
{101, "John", 50000.0}, // First employee
{102, "Alice", 60000.0}, // Second employee
{103, "Bob", 55000.0} // Third employee
};

// Loop through the array to display employee details


for (int i = 0; i < 3; i++) {
printf("Employee %d:\n", i + 1);
printf(" ID: %d\n", emp[i].id);
printf(" Name: %s\n", emp[i].name);
printf(" Salary: %.2f\n", emp[i].salary);
}
return 0;
}

Output
Employee 1:
ID: 101
Name: John
Salary: 50000.00
Employee 2:
ID: 102
Name: Alice
Salary: 60000.00
Employee 3:
ID: 103
Name: Bob
Salary: 55000.00

Advantages of Array of Structures

1. Simplifies management of multiple records of the same type.


2. Improves readability and maintainability by logically grouping related data.
3. Supports dynamic and static initialization of records.
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

Pointer to Structure

A pointer to a structure is a variable that stores the address of a structure


variable. It provides an efficient way to access structure members using the
arrow operator (->).

Key Points

1. A structure pointer stores the memory address of a structure.


2. Members of the structure can be accessed using the arrow operator (->).
3. Useful for passing structures to functions, especially in large data structures.

Syntax
struct StructureName {
data_type member1;
data_type member2;
// Additional members
};

struct StructureName *ptr; // Pointer to structure

Example with Explanation


#include <stdio.h>

// Define a structure
struct Employee {
int id; // Employee ID
char name[50]; // Employee name
float salary; // Employee salary
};

int main() {
struct Employee emp = {101, "John", 50000.0}; // Initialize a structure variable

struct Employee *ptr = &emp; // Pointer to the structure

// Access and display structure members using the pointer


printf("Employee Details:\n");
printf(" ID: %d\n", ptr->id);
printf(" Name: %s\n", ptr->name);
printf(" Salary: %.2f\n", ptr->salary);

// Modify structure members through the pointer


ptr->salary = 55000.0;
printf("\nAfter Updating Salary:\n");
printf(" Salary: %.2f\n", ptr->salary);

return 0;
}
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

Output
Employee Details:
ID: 101
Name: John
Salary: 50000.00

After Updating Salary:


Salary: 55000.00

Example: Pointer to Structure Array


#include <stdio.h>

struct student {
int roll;
char name[50];
float percentage;
};

int main() {
// Array of structures
struct student students[3] = {
{1, "Alice", 85.5},
{2, "Bob", 90.2},
{3, "Charlie", 78.0}
};

// Pointer to structure
struct student *ptr = students; // Pointer points to the first element of the array

// Access structure elements using the pointer


for (int i = 0; i < 3; i++) {
printf("Student %d:\n", i + 1);
printf(" Roll: %d\n", (ptr + i)->roll); // Accessing using pointer arithmetic
printf(" Name: %s\n", (ptr + i)->name);
printf(" Percentage: %.2f\n\n", (ptr + i)->percentage);
}

return 0;
}

Explanation:

1. Structure Array:
o students[3] is an array of struct student, containing information for 3
students.
2. Pointer to Structure Array:
o The pointer ptr points to the first element of the students array (ptr =
students).
3. Pointer Arithmetic:
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

o (ptr + i) points to the i-th element of the array.


o Use the -> operator to access the members of the structure.
4. Loop Through Array:
o A for loop is used to iterate through the array, and the pointer is
incremented using pointer arithmetic.

Output:
Student 1:
Roll: 1
Name: Alice
Percentage: 85.50

Student 2:
Roll: 2
Name: Bob
Percentage: 90.20

Student 3:
Roll: 3
Name: Charlie
Percentage: 78.00

Advantages of Pointer to Structure

1. Efficient in memory usage, especially when dealing with large structures.


2. Allows passing structures by reference to functions without copying the entire
structure.
3. Enables dynamic allocation of structures at runtime using malloc().

Comparison of Array of Structures and Pointer to Structures

Aspect Array of Structures Pointer to Structure

Allocates memory for all elements at Allocates memory for a single


Memory
once. structure or dynamically for multiple.

Access members using Access members using pointer-


Access
array[index].member. >member.

Best for fixed-size collections of Best for dynamic structures or


Use Case
records. passing structures to functions.

May consume more memory as all Efficient in terms of memory and


Efficiency
elements are stored. passing large structures.
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

Unions in C

A union in C is a user-defined data type similar to a structure. However, unlike


structures, all members of a union share the same memory location. This
means only one member can hold a value at any given time. Unions are
typically used when memory efficiency is a concern.

Syntax

union UnionName {
data_type member1;
data_type member2;
// Additional members
};

Example

#include <stdio.h>

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

int main() {
union Data data;

// Assign and print integer value


data.i = 10;
printf("Integer: %d\n", data.i);

// Assign and print float value


data.f = 220.5;
printf("Float: %.1f\n", data.f);

// Assign and print string value


snprintf(data.str, sizeof(data.str), "C Programming");
printf("String: %s\n", data.str);

// Observe how overwriting affects memory


printf("Integer after string assignment: %d\n", data.i);

return 0;
}

Output

Integer: 10
Float: 220.5
String: C Programming
Integer after string assignment: 1129270631
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

Explanation

1. Only one member of the union can hold a value at a time.


2. Writing to one member overwrites the previous value since all members
share the same memory.
3. Memory allocated to a union equals the size of its largest member.

Comparison of Structures and Unions

Feature Structure Union


Memory Each member has its own All members share the same
Allocation memory. memory.
Size Sum of the sizes of all members. Size of the largest member.
All members can be accessed Only one member can hold a
Access
simultaneously. value at a time.
Used when members are Used for memory-efficient
Use Case
independent. storage of data.

Example to Compare Memory Usage

#include <stdio.h>

struct StructureExample {
int i;
float f;
char str[20];
};

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

int main() {
printf("Size of Structure: %lu bytes\n", sizeof(struct StructureExample));
printf("Size of Union: %lu bytes\n", sizeof(union UnionExample));
return 0;
}

Output

Size of Structure: 28 bytes


Size of Union: 20 bytes
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

Bit Fields

A bit field allows assigning a specific number of bits to structure members,


enabling memory-efficient representation of data. Bit fields are particularly
useful for flags or representing binary data (e.g., hardware registers).

Syntax

struct BitFieldName {
unsigned int member1 : bit_count; // Allocate 'bit_count' bits to member1
unsigned int member2 : bit_count; // Allocate 'bit_count' bits to member2
};

Example

#include <stdio.h>

// Define a structure with bit fields


struct BitField {
unsigned int a : 3; // 3 bits for 'a' (0 to 7)
unsigned int b : 2; // 2 bits for 'b' (0 to 3)
};

int main() {
struct BitField bit;

bit.a = 5; // Binary: 101


bit.b = 3; // Binary: 11

printf("a: %u, b: %u\n", bit.a, bit.b);

// Example of overflow
bit.a = 10; // Binary: 1010 (truncated to 3 bits)
printf("After assigning 10 to 'a': %u\n", bit.a);

return 0;
}

Output

a: 5, b: 3
After assigning 10 to 'a': 2

Explanation

1. Bit Allocation: Each member is assigned a specific number of bits.


o a uses 3 bits, so its range is 0 to 23−1=7.
o b uses 2 bits, so its range is 0 to 22−1=3.
2. Memory Efficiency: Instead of allocating an entire int for each member,
only the specified bits are used.
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

3. Overflow: If a value exceeds the allotted bits, it wraps around or


truncates.

Advantages of Bit Fields

1. Memory Efficiency: Saves memory by limiting the number of bits used


for each member.
2. Useful for Compact Data: Ideal for flags or compact data representation
(e.g., hardware registers).

Limitations of Bit Fields

1. Platform Dependency: Behavior may vary between compilers and


platforms.
2. No Pointers to Bit Fields: You cannot take the address of a bit field
member.

Programs

Write a C program to find the total, average of n students using structures

#include <stdio.h>

// Define a structure to store student details


struct Student {
char name[50];
int marks;
};

int main() {
int n, i;
float total = 0, average;

// Input the number of students


printf("Enter the number of students: ");
scanf("%d", &n);

// Create an array of structures


struct Student students[n];

// Input details for each student


for (i = 0; i < n; i++) {
printf("Enter name of student %d: ", i + 1);
scanf("%s", students[i].name);
printf("Enter marks of student %d: ", i + 1);
scanf("%d", &students[i].marks);
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

total += students[i].marks; // Add marks to total


}

// Calculate average
average = total / n;

// Display the results


printf("\nStudent Details:\n");
printf("-----------------\n");
for (i = 0; i < n; i++) {
printf("Name: %s, Marks: %d\n", students[i].name, students[i].marks);
}
printf("\nTotal Marks: %.2f\n", total);
printf("Average Marks: %.2f\n", average);

return 0;
}

Demonstrate the differences between structures and unions using


a C program
#include <stdio.h>

// Define a structure
struct MyStruct {
int intVal;
float floatVal;
char charVal;
};

// Define a union
union MyUnion {
int intVal;
float floatVal;
char charVal;
};

int main() {
struct MyStruct s = {1, 2.5, 'A'};
union MyUnion u;

// Assign values to the union


u.intVal = 1;
u.floatVal = 2.5; // Overwrites intVal
u.charVal = 'A'; // Overwrites floatVal

// Display structure values


printf("Structure:\n");
printf("intVal: %d, floatVal: %.2f, charVal: %c\n", s.intVal, s.floatVal, s.charVal);
K D V PAVAN KUMAR VARMA, DEPT OF CSE, SRKREC

// Display union values


printf("\nUnion:\n");
printf("intVal: %d, floatVal: %.2f, charVal: %c\n", u.intVal, u.floatVal, u.charVal);

return 0;
}

Write a C program to copy one structure variable to another


structure of the same type
#include <stdio.h>
#include <string.h>

// Define a structure
struct Student {
char name[50];
int age;
float marks;
};

int main() {
// Initialize a structure
struct Student student1 = {"Alice", 20, 85.5};

// Copy structure
struct Student student2 = student1;

// Modify copied structure to show independence


strcpy(student2.name, "Bob");
student2.age = 22;

// Display both structures


printf("Student 1: Name = %s, Age = %d, Marks = %.2f\n", student1.name, student1.age,
student1.marks);
printf("Student 2: Name = %s, Age = %d, Marks = %.2f\n", student2.name, student2.age,
student2.marks);

return 0;
}

You might also like