Unit 6 - Notes
CSE109
Unit 6: Derived Types
1. Introduction to Derived Types
In computer programming (specifically C), Derived Types are data types that are constructed from fundamental (primitive) data types like int, char, float, etc. They allow programmers to organize complex data more efficiently. The two most significant derived types for data organization are Structures and Unions.
2. Structure: Declaration
A Structure is a user-defined data type that allows you to combine data items of different kinds (heterogeneous data) under a single name. Each data item in a structure is called a member or field.
Syntax
The struct keyword is used to declare a structure.
struct structure_tag_name {
data_type member1;
data_type member2;
// ...
data_type memberN;
};
Key Concepts
- struct: The keyword used to define a structure.
- tag_name: The name of the structure type.
- members: Variables declared inside the braces.
- Terminating Semicolon: The declaration must end with a semicolon
;.
Example
struct Student {
char name[50];
int roll_number;
float marks;
};
Note: This declaration does not allocate memory. It only creates a template (blueprint).
3. Definition and Initialization of Structures
Definition (Creating Structure Variables)
Memory is allocated only when structure variables are defined.
Method 1: During Declaration
struct Point {
int x;
int y;
} p1, p2; // p1 and p2 are variables of type 'struct Point'
Method 2: Separate Definition
struct Point {
int x;
int y;
};
// Inside main function
struct Point p1;
struct Point p2;
Initialization
Structures can be initialized at the time of definition, similar to arrays.
1. Sequential Initialization (Compile-time)
Values are assigned in the order members are declared.
struct Student s1 = {"John Doe", 101, 89.5};
2. Designated Initialization (C99 Standard)
Allows initializing members by name, in any order.
struct Point p1 = {.y = 10, .x = 5};
3. Partial Initialization
If fewer values are provided than members, the remaining members are initialized to 0 (or NULL).
struct Point p1 = {10}; // x = 10, y = 0
4. Accessing Structure Members
Structure members are accessed using the Member Access Operator, commonly known as the Dot Operator (.).
Syntax
structure_variable_name.member_name
Example Code
#include <stdio.h>
#include <string.h>
struct Book {
char title[50];
int id;
float price;
};
int main() {
struct Book b1;
// Assigning values via dot operator
b1.id = 1001;
b1.price = 25.50;
strcpy(b1.title, "C Programming");
// accessing values to print
printf("Title: %s\n", b1.title);
printf("ID: %d\n", b1.id);
return 0;
}
5. Structures and Pointers
A pointer that points to a structure variable is called a structure pointer. This is crucial for passing structures to functions efficiently (by reference) and for dynamic memory allocation (Linked Lists, Trees).
Declaration
struct Student *ptr;
Initialization
struct Student s1 = {"Alice", 1, 90.0};
ptr = &s1; // ptr now holds the address of s1
Accessing Members via Pointer
There are two ways to access members using a pointer:
- Dereferencing + Dot Operator:
(*ptr).member(Parentheses are mandatory because.has higher precedence than*). - Arrow Operator (
->):
ptr->member(This is the standard and preferred method).
Example
struct Rect {
int length;
int width;
};
struct Rect r = {10, 20};
struct Rect *p = &r;
// Accessing
printf("%d", (*p).length); // Prints 10
printf("%d", p->width); // Prints 20
6. Array of Structure and Array Inside Structure
Array of Structure
Instead of declaring separate variables for 100 students (s1, s2, ... s100), we use an array of structures.
Syntax: struct struct_name array_name[size];
Example:
struct Employee {
int id;
char name[20];
};
struct Employee emp[3]; // Array of 3 Employee structures
// Accessing elements
emp[0].id = 1;
strcpy(emp[0].name, "Alex");
emp[1].id = 2; // etc...
Array Inside Structure
A structure member can itself be an array.
Example:
struct Student {
char name[20];
int marks[5]; // Array inside structure to hold marks of 5 subjects
};
struct Student s1;
s1.marks[0] = 95; // Accessing the first mark of student s1
7. Nested Structures (Structure Inside Structure)
A structure can contain another structure as its member. This is used to create complex data models.
Declaration and Definition
struct Date {
int day;
int month;
int year;
};
struct Employee {
int id;
char name[20];
struct Date doj; // Nested structure: Date of Joining
};
Initialization
Nested braces are used for initialization.
struct Employee e1 = {101, "Robert", {12, 11, 2023}};
Accessing Nested Members
Chaining of the dot operator is required.
Syntax: outer_variable.inner_variable.member
e1.doj.day = 15;
printf("Join Year: %d", e1.doj.year);
8. Unions
Definition
A Union is a user-defined data type similar to a structure, but with a critical difference in memory allocation.
- Structure: Allocates memory for all members (Sum of sizes of members).
- Union: Allocates memory only for the largest member. All members share this same memory location.
Declaration and Initialization
The syntax uses the union keyword.
union Data {
int i;
float f;
char str[20];
};
Memory Analysis of the above example:
int= 4 bytesfloat= 4 bytesstr= 20 bytes- Total Size of Union Data: 20 bytes (the size of the largest member,
str).
Initialization
Only the first member of the union can be initialized directly during declaration (unless using designated initializers in C99).
union Data d1 = {10}; // Valid: initializes 'i'
9. Accessing Union Members
Union members are accessed using the dot operator (.) for variables and arrow operator (->) for pointers, exactly like structures.
Crucial Behavior:
Since memory is shared, only one member can contain a valid value at any given time. Modifying one member will corrupt the values of other members.
Example Code
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 10;
printf("data.i: %d\n", data.i); // Prints 10
data.f = 220.5;
printf("data.f: %f\n", data.f); // Prints 220.5
printf("data.i: %d\n", data.i); // Garbage value! (Memory of 'i' was overwritten by 'f')
strcpy(data.str, "C Programming");
printf("data.str: %s\n", data.str);
printf("data.f: %f\n", data.f); // Garbage value!
return 0;
}
Summary Comparison: Structure vs. Union
| Feature | Structure | Union |
|---|---|---|
| Keyword | struct |
union |
| Memory Allocation | Sum of the size of all members. | Size of the largest member only. |
| Value Access | All members can store values simultaneously. | Only one member is active at a time. |
| Alteration | Altering one member does not affect others. | Altering one member overwrites others. |
| Use Case | Grouping related data (e.g., Student Record). | Memory saving or type punning (interpreting same bits as different types). |