Chapter 6: Pointers – Handle With Care
Understand pointers and how to use them safely in C.
Chapter 6: Pointers – Handle With Care
Table of Contents
- Table of Contents
- 6.1 What Are Pointers?
- 6.2 Pointer Syntax and Usage
- 6.3 Common Pointer Pitfalls
- 6.4 Exercises
- 6.5 Solutions
- 6.6 What’s Coming in the Next Chapter
6.1 What Are Pointers?
A pointer is a variable that stores the address of another variable.
1
2
int x = 10;
int *p = &x;
6.2 Pointer Syntax and Usage
*
is used to declare a pointer and to dereference it.&
is used to get the address of a variable.
6.3 Common Pointer Pitfalls
- Uninitialized pointers
- Dangling pointers
- Pointer arithmetic
6.4 Exercises
- Declare a pointer to an integer and assign it the address of a variable.
- Write a program that swaps two integers using pointers.
- What happens if you dereference a NULL pointer?
6.5 Solutions
6.5.1 Solution 1
1
2
int x = 5;
int *p = &x;
6.5.2 Solution 2
1
2
3
4
5
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
6.5.3 Solution 3
Dereferencing a NULL pointer causes undefined behavior (often a crash).
6.6 What’s Coming in the Next Chapter
Next, you’ll learn about arrays and strings in C!
This post is licensed under CC BY 4.0 by the author.