What is a Struct?
Part of the Logic & Flow section of Coddy's C journey — lesson 38 of 63.
Up until now, you've worked with C's built-in data types like int, float, and char. But what if you need to group related information together? This is where structures, or structs, become invaluable.
A struct is a user-defined data type that allows you to combine multiple variables of different types under a single name. Think of it as a container that holds related pieces of information together.
Consider a student record system. Instead of managing separate variables for each piece of student information, you can group them together:
// Instead of separate variables:
char student_name[50];
int student_id;
float student_grade;
// You can group them in a struct:
struct Student {
char name[50];
int id;
float grade;
};This approach makes your code more organized and easier to understand. When you see a struct Student, you immediately know it contains all the essential information about a student. Structures are fundamental building blocks that help you model real-world entities in your programs, making your code more logical and maintainable.
Cheat sheet
A struct is a user-defined data type that groups multiple variables of different types under a single name:
struct Student {
char name[50];
int id;
float grade;
};Structures help organize related data together, making code more logical and maintainable compared to using separate variables.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters7Structures (structs)
What is a Struct?Declaring a StructCreating Struct VariablesAccessing Struct MembersInitializing StructsRecap: Student Data Struct2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions