Structure and Union
By Notes Vandar
Structure and Union
A structure (also known as a struct
) is a user-defined data type that groups variables of different data types under a single name. Each variable in the structure is called a member of the structure.
6.1 Concept of Structure
A structure (also known as a struct
) is a user-defined data type that groups variables of different data types under a single name. Each variable in the structure is called a member of the structure.
Syntax of Structure
data_type member1;
data_type member2;
…
};
Example: Structure Declaration and Usage
#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person person1;
// Assigning values to members
strcpy(person1.name, “John”);
person1.age = 25;
person1.height = 5.9;
// Accessing and printing members
printf(“Name: %s\n”, person1.name);
printf(“Age: %d\n”, person1.age);
printf(“Height: %.2f\n”, person1.height);
return 0;
}
Accessing Structure Members
- Use the dot operator (
.
) to access the members of a structure. - You can also use a pointer to a structure and access members using the arrow operator (
->
).
Example with Pointers:
#include <stdio.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person person1 = {“Alice”, 30};
struct Person *ptr = &person1;
// Accessing structure members using pointers
printf(“Name: %s\n”, ptr->name);
printf(“Age: %d\n”, ptr->age);
return 0;
}
Advantages of Structures
- Group different data types together under a single name.
- Can be used to create more complex data types such as linked lists, trees, and graphs.
6.2 Initializing, accessing member of structure
Once a structure is defined in C, you can create variables of that structure type. After creating these structure variables, you can initialize and access their members to work with them.
1. Initializing Structure Members
You can initialize structure members in two main ways:
a. Default Initialization After Declaration
This approach allows you to initialize the structure members after declaring the structure variable.
Example:
#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person person1;
// Initializing structure members
strcpy(person1.name, “Alice”); // Assign a string to ‘name’
person1.age = 25; // Assign an integer to ‘age’
person1.height = 5.6; // Assign a float to ‘height’
return 0;
}
- In the above example, the structure
Person
is declared, and then each member (name
,age
, andheight
) is assigned a value separately.
b. Initialization During Declaration
You can also initialize a structure at the time of declaration.
Example:
#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Initializing members while declaring the structure variable
struct Person person1 = {“Alice”, 25, 5.6};
return 0;
}
- In this case, the structure
person1
is initialized when it is declared. Each member (name
,age
, andheight
) is given a value right away.
c. Partial Initialization
If you do not provide values for all members during initialization, the remaining members are automatically initialized to zero (for numeric types) or an empty value (for arrays).
Example:
2. Accessing Members of a Structure
After initializing a structure, you can access its members using the dot operator (.
). The dot operator is used to access the members of a structure variable.
Example: Accessing Structure Members
#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person person1 = {“Alice”, 25, 5.6};
// Accessing and printing structure members
printf(“Name: %s\n”, person1.name);
printf(“Age: %d\n”, person1.age);
printf(“Height: %.2f\n”, person1.height);
return 0;
}
Accessing Structure Members with Pointers
When you have a pointer to a structure, you can access its members using the arrow operator (->
).
Example:
#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person person1 = {“Alice”, 25, 5.6};
struct Person *ptr = &person1; // Pointer to structure
// Accessing structure members using pointer
printf(“Name: %s\n”, ptr->name);
printf(“Age: %d\n”, ptr->age);
printf(“Height: %.2f\n”, ptr->height);
return 0;
}
- Here,
ptr->name
is equivalent to(*ptr).name
. The arrow operator simplifies the syntax when working with pointers to structures.
3. Example: Combining Initialization and Accessing
#include <stdio.h>
struct Book {
char title[100];
char author[50];
int pages;
float price;
};
int main() {
// Initializing the structure ‘book1’
struct Book book1 = {“C Programming”, “Dennis Ritchie”, 300, 29.99};
// Accessing and displaying the values of ‘book1’
printf(“Title: %s\n”, book1.title);
printf(“Author: %s\n”, book1.author);
printf(“Pages: %d\n”, book1.pages);
printf(“Price: $%.2f\n”, book1.price);
return 0;
}
In this example, the structure Book
is used to represent the properties of a book, and the members are initialized during declaration. The values are then accessed using the dot operator and displayed.
6.3 Array of structure
An array of structures is essentially an array where each element is a structure. This allows you to store multiple records of data, each containing several fields. Arrays of structures are useful when you need to work with multiple instances of structured data, such as storing information about several people, books, students, or any other entities
1. Declaration of Array of Structures
The syntax for declaring an array of structures is similar to that of arrays, except the data type is a structure.
Syntax
struct structure_name {
data_type member1;
data_type member2;
…
};
struct structure_name array_name[size];
structure_name
: The name of the structure you have defined.array_name
: The name of the array of structures.size
: The number of elements in the array.
Example: Declaring an Array of Structures
#include <stdio.h>
// Define a structure ‘Person’
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Declare an array of structures of size 3
struct Person people[3];
return 0;
}
In this example, people
is an array of 3 Person
structures, where each element of the array can store data for one person.
2. Initializing an Array of Structures
Just like normal arrays, you can initialize an array of structures in two ways: by initializing members individually or by initializing the entire array at once.
a. Initializing Members Individually
You can initialize each structure in the array individually by accessing each member with the dot operator.
#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person people[3];
// Initializing the first person
strcpy(people[0].name, “Alice”);
people[0].age = 30;
people[0].height = 5.5;
// Initializing the second person
strcpy(people[1].name, “Bob”);
people[1].age = 25;
people[1].height = 6.0;
// Initializing the third person
strcpy(people[2].name, “Charlie”);
people[2].age = 28;
people[2].height = 5.9;
return 0;
}
b. Initializing the Array of Structures at Declaration
You can initialize the array of structures at the time of declaration as well:
#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Declare and initialize an array of structures
struct Person people[3] = {
{“Alice”, 30, 5.5},
{“Bob”, 25, 6.0},
{“Charlie”, 28, 5.9}
};
return 0;
}
3. Accessing Members of an Array of Structures
To access the members of a specific structure in the array, use the array index and the dot operator (.
).
Example: Accessing and Displaying Structure Members
#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person people[3] = {
{“Alice”, 30, 5.5},
{“Bob”, 25, 6.0},
{“Charlie”, 28, 5.9}
};
// Access and display the details of the first person
printf(“Person 1: \n”);
printf(“Name: %s\n”, people[0].name);
printf(“Age: %d\n”, people[0].age);
printf(“Height: %.2f\n\n”, people[0].height);
// Access and display the details of the second person
printf(“Person 2: \n”);
printf(“Name: %s\n”, people[1].name);
printf(“Age: %d\n”, people[1].age);
printf(“Height: %.2f\n\n”, people[1].height);
return 0;
}
Output:
Person 1:
Name: Alice
Age: 30
Height: 5.50
Person 2:
Name: Bob
Age: 25
Height: 6.00
Using Loops to Access Array of Structures
You can use loops to iterate through the array of structures and access each structure’s members.
#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person people[3] = {
{“Alice”, 30, 5.5},
{“Bob”, 25, 6.0},
{“Charlie”, 28, 5.9}
};
// Loop through the array of structures and print the details
for (int i = 0; i < 3; i++) {
printf(“Person %d: \n”, i + 1);
printf(“Name: %s\n”, people[i].name);
printf(“Age: %d\n”, people[i].age);
printf(“Height: %.2f\n\n”, people[i].height);
}
return 0;
}
Output:
Person 1:
Name: Alice
Age: 30
Height: 5.50
Person 2:
Name: Bob
Age: 25
Height: 6.00
Person 3:
Name: Charlie
Age: 28
Height: 5.90
4. Advantages of Array of Structures
- Efficient Data Storage: It allows you to store multiple records (each a structure) in a contiguous block of memory.
- Easier to Manage: Array of structures makes it easier to manage multiple sets of related data.
- Combined Power: Combines the power of arrays and structures to handle structured data in bulk, such as a list of students, employees, or products.
6.4 Pointer to structure
If you have defined a derived data type using the keyword struct, then you can declare a variable of this type. Hence, you can also declare a pointer variable to store its address. A pointer to struct is thus a variable that refers to a struct variable. In C, a pointer to a structure is used to hold the address of a structure. This allows you to manipulate the structure without copying the entire structure’s contents. Here’s a basic example of how you can use pointers to structures in C:
Defining a structure:
#include <stdio.h>
// Define a structure called Person
struct Person {
char name[50];
int age;
float height;
};
Using a pointer to a structure:
int main() {
// Declare and initialize a structure
struct Person person1 = {“John Doe”, 30, 5.9};
// Declare a pointer to the structure
struct Person *ptr;
// Assign the address of person1 to the pointer
ptr = &person1;
// Access and modify structure members using the pointer
printf(“Name: %s\n”, ptr->name);
printf(“Age: %d\n”, ptr->age);
printf(“Height: %.1f\n”, ptr->height);
// Modifying structure members through the pointer
ptr->age = 31;
printf(“Updated Age: %d\n”, ptr->age);
return 0;
}
struct Person *ptr;
: Declares a pointer to a structure of typePerson
.ptr = &person1;
: Assigns the address ofperson1
to the pointerptr
.ptr->name
,ptr->age
,ptr->height
: Accesses the members of the structure using the pointer. The->
operator is used to dereference the pointer and access the structure members.
In C, a union
is a user-defined data type similar to a struct
, but with a key difference: all members of a union share the same memory location. This means that at any given time, a union can hold a value for only one of its members, as they overlap in memory.
Defining and Using a Union:
Here’s an example that demonstrates the basic syntax and usage of a union
in C:
Union Definition:
#include <stdio.h>
// Define a union called Data
union Data {
int i;
float f;
char str[20];
};
int main() {
// Declare a union variable
union Data data;
// Assigning values to union members one at a time
data.i = 10;
printf(“data.i: %d\n”, data.i);
data.f = 220.5;
printf(“data.f: %.2f\n”, data.f);
// Note that assigning a new value overwrites the previous value
printf(“After assigning float, data.i: %d\n”, data.i); // Undefined behavior
// Assigning a string to the union
strcpy(data.str, “C Programming”);
printf(“data.str: %s\n”, data.str);
// Again, accessing the integer value now will not be correct
printf(“After assigning string, data.i: %d\n”, data.i); // Undefined behavior
return 0;
}
Explanation:
- Shared Memory: The members of a union share the same memory. In the above example,
data.i
,data.f
, anddata.str
all use the same memory location. Therefore, assigning a value to one member will overwrite the value of the other members. - Overwriting: When you assign a value to
data.f
, it overwrites the value indata.i
, and similarly, assigning a value todata.str
overwrites both the integer and float values.
Memory Size:
The size of a union is determined by the size of its largest member, as all members share the same memory.
Example of memory sharing:
If int
is 4 bytes, float
is 4 bytes, and the string is 20 bytes, the size of the union will be 20 bytes, which is the size of its largest member (char str[20]
).
When to use a union:
Unions are useful when you need to handle multiple types of data but only need to store one type at a time. For instance:
- Efficient memory usage when dealing with multiple data types in a variable.
- Implementing a variable that can change type during program execution.
6.6 Different between union and structure
In C, both union
and struct
are user-defined data types that group different types of variables under a single name. However, they differ significantly in how they manage memory and how their members are accessed. Here are the main differences between a union
and a struct
:
1. Memory Allocation
- Structure (
struct
):- All members of a
struct
have their own separate memory locations. This means that the total size of astruct
is the sum of the sizes of all its members, plus any padding added for alignment. - Example:
struct Example {
int i; // 4 bytes
float f; // 4 bytes
char str[10]; // 10 bytes
};// Size of struct Example = 4 + 4 + 10 = 18 bytes (plus padding)
- All members of a
- Union (
union
):- All members of a
union
share the same memory location. Therefore, the size of aunion
is equal to the size of its largest member. - Example:
union Example {
int i; // 4 bytes
float f; // 4 bytes
char str[10]; // 10 bytes
};// Size of union Example = max(4, 4, 10) = 10 bytes
- All members of a
2. Member Access
- Structure (
struct
):- You can access all members of a
struct
at any time. Each member retains its own value, and updating one member does not affect the others. - Example:
struct Example ex;
ex.i = 10;
ex.f = 20.5;
strcpy(ex.str, “Hello”);
- You can access all members of a
- Union (
union
):- Only one member of a
union
can hold a value at any time. Assigning a new value to one member will overwrite the value of the other members. - Example:
union Example ex;
ex.i = 10;
ex.f = 20.5; // This will overwrite ex.i
strcpy(ex.str, “Hello”); // This will overwrite ex.f
3. Use Cases
- Only one member of a
- Structure (
struct
):- Useful when you need to group related variables together, and you want to access all these variables simultaneously.
- Commonly used to represent complex data entities like records in databases, objects in object-oriented programming, etc.
- Union (
union
):- Useful when you need to store different types of data in the same memory location but only one type at a time. This can save memory in cases where you have multiple alternative data formats.
- Commonly used in situations where a variable could be one of several types but only one type is used at a time (e.g., parsing different types of data).