In C, a structure is a user-defined data type that allows you to group different types of data under a single name. This is useful when you need to represent a record or an entity that has multiple attributes, potentially of different types.
1. Defining a Structure
You define a structure using the struct
keyword. A structure can contain members of different data types, including other structures, arrays, and pointers.
Syntax to define a structure:
struct structure_name {
data_type member1;
data_type member2;
...
};
Example 1: Basic Structure
#include <stdio.h>
// Define a structure for a student
struct Student {
char name[50];
int age;
float marks;
};
int main() {
// Declare and initialize a variable of type 'struct Student'
struct Student student1 = {"Alice", 20, 88.5};
// Accessing structure members using dot (.) operator
printf("Name: %s\n", student1.name);
printf("Age: %d\n", student1.age);
printf("Marks: %.2f\n", student1.marks);
return 0;
}
Explanation:
- Structure Declaration: We define a structure
Student
that has three members:name
,age
, andmarks
. - Structure Initialization: We initialize a
Student
structure,student1
, with specific values forname
,age
, andmarks
. - Accessing Structure Members: We use the dot operator (
.
) to access individual members of the structure and print them.
Output:
Name: Alice
Age: 20
Marks: 88.50
2. Accessing Structure Members
To access or modify the members of a structure, you use the dot operator (.
) when working with a structure variable.
Example 2: Accessing and Modifying Members
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p1 = {2, 3};
// Access and modify structure members
printf("Original coordinates: (%d, %d)\n", p1.x, p1.y);
// Modify values
p1.x = 10;
p1.y = 20;
printf("Modified coordinates: (%d, %d)\n", p1.x, p1.y);
return 0;
}
Output:
Original coordinates: (2, 3)
Modified coordinates: (10, 20)
3. Passing Structures to Functions
Structures can be passed to functions in the same way as any other data type. You can pass them either by value or by reference.
a) Passing by Value (Creates a copy of the structure):
#include <stdio.h>
struct Rectangle {
int length;
int width;
};
// Function to calculate area of rectangle
int calculateArea(struct Rectangle r) {
return r.length * r.width;
}
int main() {
struct Rectangle rect = {10, 5};
// Pass structure by value
printf("Area: %d\n", calculateArea(rect));
return 0;
}
b) Passing by Reference (Pass the address of the structure, which allows modification):
#include <stdio.h>
struct Rectangle {
int length;
int width;
};
// Function to modify rectangle dimensions
void modifyRectangle(struct Rectangle *r) {
r->length = 15; // Access members using pointer
r->width = 7;
}
int main() {
struct Rectangle rect = {10, 5};
printf("Before modification: Length = %d, Width = %d\n", rect.length, rect.width);
// Pass structure by reference (pointer)
modifyRectangle(&rect);
printf("After modification: Length = %d, Width = %d\n", rect.length, rect.width);
return 0;
}
Explanation:
- Passing by Value: The structure is passed as a copy to the function, so any changes made inside the function will not affect the original structure.
- Passing by Reference: The address of the structure is passed to the function, which allows the function to modify the original structure.
4. Returning Structures from Functions
You can return structures from functions. Since returning large structures by value can be inefficient, structures are often returned by reference (using pointers) or via dynamic memory allocation.
Example 3: Returning a Structure from a Function
#include <stdio.h>
struct Complex {
float real;
float imaginary;
};
// Function to add two complex numbers
struct Complex addComplex(struct Complex c1, struct Complex c2) {
struct Complex result;
result.real = c1.real + c2.real;
result.imaginary = c1.imaginary + c2.imaginary;
return result; // Return structure by value
}
int main() {
struct Complex c1 = {3.5, 2.5};
struct Complex c2 = {1.5, 4.5};
struct Complex sum = addComplex(c1, c2);
printf("Sum of complex numbers: %.2f + %.2fi\n", sum.real, sum.imaginary);
return 0;
}
Explanation:
- We define a structure
Complex
to represent complex numbers. - The
addComplex()
function returns a newComplex
structure that contains the sum of two complex numbers. - The structure is returned by value.
Output:
Sum of complex numbers: 5.00 + 7.00i
5. Nested Structures
You can also have structures inside other structures, which is useful for representing more complex data.
Example 4: Nested Structures
#include <stdio.h>
struct Date {
int day;
int month;
int year;
};
struct Employee {
char name[50];
int id;
struct Date birthdate; // Nested structure
};
int main() {
struct Employee emp = {"John Doe", 101, {15, 6, 1990}};
printf("Employee Details:\n");
printf("Name: %s\n", emp.name);
printf("ID: %d\n", emp.id);
printf("Birthdate: %d-%d-%d\n", emp.birthdate.day, emp.birthdate.month, emp.birthdate.year);
return 0;
}
Explanation:
- Nested Structure: The
Employee
structure contains aDate
structure as one of its members. This represents the employee’s birthdate as a separate structure.
Output:
Employee Details:
Name: John Doe
ID: 101
Birthdate: 15-6-1990
6. Structure and Array of Structures
You can create arrays of structures, which is useful when dealing with multiple records of the same type.
Example 5: Array of Structures
#include <stdio.h>
struct Book {
char title[50];
char author[50];
int year;
};
int main() {
struct Book books[3] = {
{"The C Programming Language", "Brian Kernighan", 1978},
{"The Pragmatic Programmer", "Andrew Hunt", 1999},
{"Clean Code", "Robert C. Martin", 2008}
};
for (int i = 0; i < 3; i++) {
printf("Book %d:\n", i+1);
printf("Title: %s\n", books[i].title);
printf("Author: %s\n", books[i].author);
printf("Year: %d\n\n", books[i].year);
}
return 0;
}
Explanation:
- Array of Structures: We define an array
books
with 3Book
structures. Each element of the array is a structure that contains details about a book.
Output:
Book 1:
Title: The C Programming Language
Author: Brian Kernighan
Year: 1978
Book 2:
Title: The Pragmatic Programmer
Author: Andrew Hunt
Year: 1999
Book 3:
Title: Clean Code
Author: Robert C. Martin
Year: 2008
Conclusion:
- A structure in C is a powerful tool for grouping different data types into a single unit.
- Structures can be passed to functions by value or by reference, and can also be returned from functions.
- Structures can be nested, and you can create arrays of structures for managing collections of similar objects.
- Structures help organize data and allow for more readable and maintainable code.