Ad Space
An array of structures is a collection of multiple structure variables of the same type, stored in a contiguous block of memory. It is similar to an array of int or char, but each element of the array is an entire structure.
This is extremely useful for storing records, such as a list of students, a database of employees, or a catalog of products, where each item has the same set of properties.
Syntax:
struct structure_name variable_name[size];
Example:
Let's define a struct Student and create an array to hold records for 3 students.
#include <stdio.h>
#include <string.h>
struct Student {
int roll_no;
char name[50];
float gpa;
};
int main() {
// Declare an array of 3 structures
struct Student class[3];
int i;
// --- Initialize the array elements ---
class[0].roll_no = 101;
strcpy(class[0].name, "Alice");
class[0].gpa = 8.5;
class[1].roll_no = 102;
strcpy(class[1].name, "Bob");
class[1].gpa = 9.1;
class[2].roll_no = 103;
strcpy(class[2].name, "Charlie");
class[2].gpa = 7.8;
// --- Accessing the array elements using a loop ---
printf("--- Student Records ---\n");
for (i = 0; i < 3; i++) {
printf("Student %d:\n", i + 1);
// Access members of each element using the dot operator
printf(" Roll No: %d\n", class[i].roll_no);
printf(" Name: %s\n", class[i].name);
printf(" GPA: %.2f\n", class[i].gpa);
}
return 0;
}
A nested structure is a structure that contains another structure as one of its members. This allows you to create more complex and organized data types.
For example, an Employee structure might contain a Date structure for their date of birth, or an Address structure for their contact details.
Example:
Let's create an Employee structure that has a nested struct Date for the date of joining (doj).
#include <stdio.h>
// Define the inner structure first
struct Date {
int day;
int month;
int year;
};
// Define the outer structure
struct Employee {
int emp_id;
char name[50];
struct Date doj; // 'doj' is a nested structure variable
};
int main() {
// Declare and initialize a nested structure
struct Employee emp1 = {
1001,
"Dave",
{25, 10, 2022} // {day, month, year} for 'doj'
};
// --- Accessing members of a nested structure ---
// Use two dot operators
printf("--- Employee Details ---\n");
printf("ID: %d\n", emp1.emp_id);
printf("Name: %s\n", emp1.name);
// Accessing the nested members
printf("Date of Joining: %d-%d-%d\n",
emp1.doj.day,
emp1.doj.month,
emp1.doj.year);
return 0;
}
(These questions are identical).
The primary difference between structures and unions is how they store their members in memory.
| Feature | Structure (struct) |
Union (union) |
|---|---|---|
| Memory Allocation | Allocates enough memory to store all of its members. The total size is the sum of the sizes of all members (plus padding). | Allocates only enough memory to store its largest member. All members share this single memory space. |
| Member Access | All members can be stored and accessed simultaneously. Each member has its own unique memory location. | Only one member can be stored and accessed at any given time. Storing a value in one member overwrites any value stored in another member. |
| Purpose | To group different but related data items that are all needed at the same time (e.g., a "student" with a name, roll number, and GPA). | To save memory when you know you will only use one of several possible members at any given time (e.g., a "value" that can be an int or a float, but never both). |
| Size | sizeof(struct) is >= sum of sizeof(all members). |
sizeof(union) is sizeof(largest member). |
Example:
#include <stdio.h>
struct MyStruct {
int i;
char c;
float f;
};
union MyUnion {
int i;
char c;
float f;
};
int main() {
// --- Structure ---
struct MyStruct s;
s.i = 10;
s.c = 'A';
s.f = 3.14;
printf("Structure Size: %lu bytes\n", sizeof(s));
// All members are stored and valid
printf("Struct: %d, %c, %.2f\n", s.i, s.c, s.f);
// --- Union ---
union MyUnion u;
u.i = 10;
u.c = 'A'; // Overwrites the integer 'i'
u.f = 3.14; // Overwrites the char 'c'
printf("\nUnion Size: %lu bytes\n", sizeof(u));
// Only the last member 'f' is valid
printf("Union: %d, %c, %.2f\n", u.i, u.c, u.f);
// u.i and u.c will print garbage or parts of the float
return 0;
}
(These questions are combined as they cover the same topic.)
What is a Structure?
A structure is a user-defined, composite data type in C. It provides a way to group several related variables of different data types (like int, char, float, arrays, even other structures) under a single name.
Need for Structures:
Imagine you want to store information about a student. You would need a roll number (int), a name (char array), and a GPA (float). Without structures, you would have to manage these as separate variables:
int roll_nos[100];char names[100][50];float gpas[100];
This is clumsy and error-prone. Structures solve this problem by allowing you to create a new data type called struct Student that logically bundles all this information together. This makes the code cleaner, more organized, and easier to manage, especially when dealing with lists of records.
Syntax and Example:
#include <stdio.h>
#include <string.h>
// 1. Defining the structure
struct Student {
int roll_no;
char name[50];
float gpa;
};
int main() {
// 2. Declaring a structure variable
struct Student s1;
// 3. (Operation) Accessing members and assigning values
s1.roll_no = 101;
strcpy(s1.name, "Alice");
s1.gpa = 9.2;
// 4. (Operation) Reading member values
printf("Student Name: %s\n", s1.name);
printf("Roll No: %d\n", s1.roll_no);
// 5. (Operation) Assignment
struct Student s2 = s1; // Copies all members from s1 to s2
printf("Copied Student Name: %s\n", s2.name);
return 0;
}
Key Operations on Structures:
struct keyword to create a template..) on a structure variable (e.g., s1.name) or the arrow operator (->) on a structure pointer (e.g., ptr->name).= operator.(These questions are similar. The answer below maintains employee records and prints those with a salary above 5000, fulfilling both prompts.)
This program uses an array of structures to store employee records. It asks the user how many employees to enter, reads their details, and then iterates through the array to print the details of only those employees whose salary is greater than 5000.
#include <stdio.h>
// Define the structure for an employee
struct Employee {
int id;
char name[100];
double salary;
};
int main() {
int n, i;
printf("How many employee records do you want to enter? ");
scanf("%d", &n);
// Declare an array of structures of size 'n'
struct Employee emp[n];
// --- Read 'n' Employee Details ---
printf("\n--- Enter Employee Details ---\n");
for (i = 0; i < n; i++) {
printf("Details for Employee %d:\n", i + 1);
printf(" Enter ID: ");
scanf("%d", &emp[i].id);
printf(" Enter Name: ");
scanf(" %[^\n]", emp[i].name); // Reads string with spaces
printf(" Enter Salary: ");
scanf("%lf", &emp[i].salary);
}
// --- Prepare and Print Payroll/Details ---
printf("\n\n--- Employees with Salary > 5000 ---\n");
printf("--------------------------------------\n");
printf("ID\tName\t\tSalary\n");
printf("--------------------------------------\n");
int found = 0;
for (i = 0; i < n; i++) {
if (emp[i].salary > 5000) {
printf("%d\t%s\t\t%.2f\n",
emp[i].id,
emp[i].name,
emp[i].salary);
found = 1;
}
}
if (!found) {
printf("No employees found with salary > 5000.\n");
}
printf("--------------------------------------\n");
return 0;
}
Ad Space