Back to course

Introduction to Structures (struct)

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 41: Introduction to Structures (struct)

A structure is a user-defined data type that groups related data items of potentially different types under a single name. This is fundamental for object organization in C.

Defining a Structure

Syntax: c struct structure_name { data_type member1; data_type member2; // ... };

Example: Defining a 'Student'

c struct Student { int id; // Integer char name[50]; // Character array (string) float gpa; };

Declaring Structure Variables

Once defined, the structure name becomes a type identifier, but it must be prefixed with struct.

1. Separate Declaration

c struct Student s1; // Declares a variable s1 of type struct Student struct Student s2 = {101, "Alex", 3.8};

2. Declaration at Definition

c struct Point { int x; int y; } p1, p2; // p1 and p2 are variables of type struct Point

Note: Defining the structure only creates the template; memory is allocated only when structure variables are declared.