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
CCode Cell
1struct Student {
2 int rollNo;
3 char name[30];
4 float marks;
5};
Output
This defines a structure type named Student. It does not create a student variable yet.

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
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4struct Student {
5 int rollNo;
6 char name[30];
7 float marks;
8};
9 
10int main(void) {
11 struct Student s1;
12 
13 s1.rollNo = 101;
14 strcpy(s1.name, "Rahul");
15 s1.marks = 88.5f;
16 
17 printf("Roll Number: %d\n", s1.rollNo);
18 printf("Name: %s\n", s1.name);
19 printf("Marks: %.1f\n", s1.marks);
20 
21 return 0;
22}
Output
Roll Number: 101
Name: Rahul
Marks: 88.5

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
CCode Cell
1#include <stdio.h>
2 
3struct Student {
4 int rollNo;
5 char name[30];
6 float marks;
7};
8 
9int main(void) {
10 struct Student s1 = {101, "Rahul", 88.5f};
11 
12 printf("%d %s %.1f\n", s1.rollNo, s1.name, s1.marks);
13 return 0;
14}
Output
101 Rahul 88.5

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