← Back to C Course | Chapter 8: Structures & Unions | Lesson 1 of 7

C Structures Introduction

What is a Structure?

Unlike an array, which requires every element to be the same type, a structure can mix an int, a float, and a char array together in one logical unit -- ideal for modeling something like a student record with a name, age, and GPA.

Example: What is a Structure?

c
#include <stdio.h>
struct Student {
	int age;
	float gpa;
	char grade;
};
int main() {
	struct Student s = {20, 3.5f, 'A'};
	printf("%d %.1f %c", s.age, s.gpa, s.grade);
	return 0;
}

Defining a Structure

The members you list inside the braces become the structure's blueprint -- no memory is actually allocated until you declare a variable of that structure type, similar to how declaring a class doesn't create an object.

Example: Defining a Structure

c
#include <stdio.h>
struct Point {
	int x;
	int y;
};
int main() {
	struct Point p;
	p.x = 3;
	p.y = 4;
	printf("%d %d", p.x, p.y);
	return 0;
}

Declaring Structure Variables

This two-step process (define the struct, then declare a variable of it) can be combined into a single statement, but writing them separately often makes larger programs easier to follow, especially when a struct is defined in a header file.

Example: Declaring Structure Variables

c
#include <stdio.h>
struct Point {
	int x;
	int y;
};
int main() {
	struct Point p1;
	p1.x = 1;
	p1.y = 2;
	printf("%d %d", p1.x, p1.y);
	return 0;
}

Accessing Structure Members

student.age = 20 both reads and writes the age field exactly like a normal variable -- the dot operator is what ties a specific member name to a specific structure variable in memory.

Example: Accessing Structure Members

c
#include <stdio.h>
struct Student {
	int age;
};
int main() {
	struct Student student;
	student.age = 20;
	printf("%d", student.age);
	return 0;
}

Array of Structures

This is the natural way to model a list of structured records, like a roster of students, since each array element is a full independent copy of the structure with its own set of member values.

Example: Array of Structures

c
#include <stdio.h>
struct Student {
	int age;
};
int main() {
	struct Student roster[2] = {{20}, {21}};
	printf("%d %d", roster[0].age, roster[1].age);
	return 0;
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.