Search⌘ K
AI Features

Comparing Pointers

Explore how to compare pointers and safely use pointer arithmetic in C. Understand dynamic offset calculation between variable addresses to avoid bugs and improve code portability. This lesson helps you grasp pointer comparisons and how to handle memory addresses regardless of variable placement on the stack.

Introduction

Pointers hold memory addresses, which are just numbers. Every comparison operator that works on numbers also works on pointers—<,>,<=,>=,==, and !=.

We won’t present an example for all of them as it will get pretty repetitive.

Fixing the code

We will try to use the comparison operator and improve the code we used in the Addition and Subtraction lesson.

C
#include <stdio.h>
int main()
{
int a = 5, b = 6;
printf("&a = %u | &b = %u\n", &a, &b);
int *ptr = &b;
printf("[Before ++]Reading thru the pointer: %d\n", *ptr); //will read the value of b
ptr++;
printf("[After ++]Reading thru the pointer: %d\n", *ptr); //will read the value of a
return 0;
}

Using the code that we previously used for incrementing and decrementing, we’ll ...