Structures
Structures in C
What is a Structure?
A Structure (often called a struct) is a user-defined data type that allows you to combine data of different types (int, char, float, etc.) into a single unit.
Think of it as a template for a record. For example, if you want to store information about a "Student," you need a name (string), a roll number (int), and marks (float). A structure allows you to wrap all of these into one "Student" variable.
Syntax
The struct keyword is used to define the template, and then you declare variables of that structure type.
data_type member1;
data_type member2;
}; // Don't forget the semicolon!
Practical Example
Example: Creating a 'Book' Record
// 1. Define the structure struct Book { char title[50]; int pages; float price; }; int main() { // 2. Declare a structure variable struct Book myBook = {"C Programming", 250, 499.50}; // 3. Access members using the dot (.) operator printf("Book: %s, Price: %.2f", myBook.title, myBook.price); return 0; }
📍 The Dot (.) Operator
To access the "insides" of a structure variable, we use a period (the dot operator). For example, myBook.pages tells the computer: "Go to the variable myBook and find the pages member inside it."
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute
🏋️ Test Yourself With Exercises
Take our quiz on Structures to test your knowledge.
Browse Quizzes »