Nearby lessons

58 of 72

C - Structure Introduction

A structure in C groups related values, even when they have different data types, under one name. In this lesson, we will learn how to define a structure, create variables, and access its members.

1. What Is a Structure?

Suppose we want to store a student's roll number, name, and marks. These values have different data types. A structure lets us keep them together as one student record.

In simple words: A structure is like a form with different fields, such as name, roll number, and marks.

Example01
Loading editor…

2. Create a Structure Variable and Access Members

After defining a structure, create a variable using struct Student. Use the dot operator (.) to access each member.

Example02
Loading editor…

3. Initialise a Structure in One Line

You can provide the values when creating the variable. Values must follow the same order as the members in the structure definition.

Example03
Loading editor…

4. Structure vs Array

An array is useful when we need many values of the same type. A structure is useful when we need to keep different details of one record together.

  • Array: stores values such as 10, 20, and 30.
  • Structure: stores a student's roll number, name, and marks together.

Common Mistakes

  • Do not forget the semicolon after the closing brace of a structure definition.
  • Use s1.rollNo, not s1-rollNo, to access a member.
  • Member names and their capitalisation must match the definition.
  • For a character array member, use strcpy() to copy a string after declaration.
📝 Key Takeaways
  • A structure groups related values of different data types.
  • The struct keyword is used to define a structure.
  • A structure definition must end with a semicolon.
  • Use the dot (.) operator to access a member.
  • An array stores values of the same type, while a structure can store different types.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.