Addition

Learn to perform addition on pointers.

Introduction

We’ll learn how to perform addition using pointers. To learn how these operations work, we’ll create variables and pointers to those variables. Then, we will print the pointer variable before and after operating on it.

Recall that memory addresses are printed in hex usually. However, in this chapter, we’ll print them in base 10 to make it easier for us to see the changes.

Increment

In the following code, we create a pointer to a char and increment it. We want to see how the address stored inside the pointer changes.

Press + to interact
#include <stdio.h>
int main()
{
char c = 'c';
char *charPtr = &c;
printf("Before increment: %u\n", charPtr);
charPtr++;
printf("After increment: %u\n", charPtr);
return 0;
}

A possible output is as follows:

Before increment: 344447575
After increment: 344447576

If we compare the result, we can see that the code performed a simple numerical addition. 344447575 + 1 = 344447576. Nothing fancy here!

The meaning behind the operation is that it moves the pointer to the following memory location (next memory byte). See the following drawing:

Let’s now change the data type from char to int and see what happens:

Press + to interact
#include <stdio.h>
int main()
{
int i = 10;
int *intPtr = &i;
printf("Before increment: %u\n", intPtr);
intPtr++;
printf("After increment: %u\n", intPtr);
return 0;
}

A possible output is as follows:

 ...