A structure is a user-defined data type that allows you to combine data items of different types under a single name. While arrays group items of the same type, structures group items that are logically related, regardless of their type.
1. Defining a Structure
A structure template (or blueprint) is defined using the struct keyword. The definition typically goes outside of any function, usually near the beginning of the source file.
Syntax:
struct structureName {
dataType member1;
dataType member2;
// ...
};
Example: Defining a Book Structure
struct Book {
char title[100]; // String (char array)
char author[50];
int pages;
float price;
};
Crucial Note: Defining the structure template does not allocate any memory; it only defines the data type layout.
2. Declaring Structure Variables
Once the structure is defined, you can declare variables of that type. This is the point where memory is allocated for the structure members.
A. Standard Declaration
// Declares 'book1' and 'book2' as variables of type struct Book
struct Book book1;
struct Book book2;
B. Combined Definition and Declaration
You can optionally declare variables immediately after the structure definition (though this is less common).
struct Point {
int x;
int y;
} p1, p2; // p1 and p2 are declared here
3. Accessing Structure Members
To access individual members of a structure variable, you use the member access operator (the dot operator .).
Syntax: structureVariable.member;
Example: Initializing and Accessing
struct Book history_book;
// 1. Assigning values using the dot operator
strcpy(history_book.title, "The Great War");
strcpy(history_book.author, "John Doe");
history_book.pages = 500;
history_book.price = 25.50;
// 2. Accessing and printing members
printf("Title: %s\n", history_book.title);
printf("Price: %.2f\n", history_book.price);
4. Initialization at Declaration
You can initialize a structure variable using initializer lists (curly braces {}) similar to arrays.
struct Book scifi_book = {"Dune", "Frank Herbert", 800, 19.99};
5. Arrays of Structures
Structures are often used to manage large collections of records. You can declare an array where each element is a structure variable.
// An array to hold data for 10 students
struct Student {
int id;
float gpa;
};
struct Student class_list[10];
// Accessing the 'gpa' member of the second student (index 1)
class_list[1].gpa = 3.85;
