Comparing Pointers
Learn to compare pointers.
We'll cover the following...
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.
#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 bptr++;printf("[After ++]Reading thru the pointer: %d\n", *ptr); //will read the value of areturn 0;}
Using the code that we previously used for incrementing and decrementing, we’ll explore the comparison operators. We had two variables on the stack. Then, we created a pointer for one of them and then incremented or decremented it to get to the other variable.
What we did falls into the undefined behavior category. That is, the code isn’t portable and not guaranteed to work. On another system, the compiler may decide to switch ...