🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

C Structures (struct) — Group Related Data

C FundamentalsC Structures🟢 Free Lesson

C Structures (struct) — Group Related Data

Learning Objectives

  • Define a structure type with named members
  • Create structure variables and access members
  • Store collections with arrays of structures
  • Pass structures to functions by value and by pointer

Why Structures Exist

Real data rarely fits into a single scalar. A student has a name, an ID, and a grade. A rectangle has width and height. A product has a title, price, and stock count. Structures let you bundle related fields under one name so the data travels and is organized as a unit.

Without structures you would juggle many parallel arrays or unrelated variables. Structures keep the fields together, make function signatures clearer, and prepare you for modeling more complex systems later.

Defining and Using a struct

You define a structure with the struct keyword, a tag name, and a list of members inside braces. After the definition, you can declare variables of that type and reach each member with the dot operator.

#include 

struct Student {
    int id;
    float gpa;
    char grade;
};

int main(void) {
    struct Student s1;

    s1.id = 101;
    s1.gpa = 3.8;
    s1.grade = 'A';

    printf("ID: %d\n", s1.id);
    printf("GPA: %.2f\n", s1.gpa);
    printf("Grade: %c\n", s1.grade);
    return 0;
}

Each member occupies its own space inside the structure. Memory layout may include padding bytes so members align efficiently on the machine. sizeof reports the total size including any padding the compiler inserts.

MemberTypical TypeExample Value
idint101
gpafloat3.8
gradecharA
namechar arrayfixed buffer or pointer

Initializing Structures

You can initialize all members at declaration time using an initializer list in the order members were declared. Designated initializers let you set specific fields by name, which is clearer when structures grow large.

struct Student s2 = {102, 3.5, 'B'};
struct Student s3 = {
    .id = 103,
    .gpa = 3.9,
    .grade = 'A'
};

Keeping initialization close to declaration reduces the chance of using a structure before its fields are filled with meaningful values.

Arrays of Structures

When you need many records of the same shape, an array of structures is the natural fit. Each element is a full structure, and you index into the array first, then access the member.

struct Student classList[3] = {
    {1, 3.5, 'B'},
    {2, 3.8, 'A'},
    {3, 3.2, 'C'}
};

for (int i = 0; i < 3; i++) {
    printf("%d %.2f %c\n",
        classList[i].id,
        classList[i].gpa,
        classList[i].grade);
}

This pattern appears everywhere from simple gradebooks to file formats that store rows of records. Loops over arrays of structures are a core skill for practical C programs.

Passing Structures to Functions

Passing a structure by value copies every member into the function, which is simple but costly for large structures. Passing a pointer avoids the copy and allows the function to update the original record.

void promote(struct Student *s) {
    s->gpa += 0.1f;
}

int main(void) {
    struct Student s = {10, 3.0, 'C'};
    promote(&s);
    printf("%.2f\n", s.gpa);
    return 0;
}

The arrow operator combines dereference and member access for pointer variables. Use dot for direct structure variables and arrow for structure pointers. Choosing the pointer form for large data avoids unnecessary copying.

📝typedef Shortcuts

Many programs pair structures with a typedef alias so later declarations read more cleanly. You will see that technique fully in the unions, enums, and typedef lesson.

Nested Structures

Structures can contain other structures. A course might embed a Student structure inside an Enrollment structure. Access flows left to right with dots or arrows depending on whether each level is a value or a pointer.

Keep nesting shallow enough to stay readable. Deep chains of members often signal that the model can be simplified or split into helper functions.

Key Takeaways

💡

  • Structures group related fields under one custom type
  • Dot accesses members on values, arrow accesses members on pointers
  • Arrays of structures store many uniform records efficiently
  • Prefer passing large structures by pointer to avoid full copies
  • Initializer lists and designated initializers make setup clear

Practice Questions

  1. What is the difference between the dot operator and the arrow operator?
  2. Why might passing a large structure by pointer be better than by value?
  3. How do you store twenty student records of the same type in one variable?

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert C Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement