DEV Community

Cover image for Introduction to Pointers
Jajuan Hall
Jajuan Hall

Posted on

Introduction to Pointers

Introduction

A pointer is a memory address. Think of a pointer like a bookmark. A bookmark references a page in a book. A pointer references an address in memory that holds a particular value: string, integer, Boolean, etc. The purpose of pointers is to create data structures such as arrays or graphs. In this post, you will learn how to declare a pointer variable and pointer operations.

Declaring Pointer Variables In C++

Declaring a pointer in C++ is the same as declaring a regular variable, except adding an asterisk behind the variable like the following example.

int* x;
Enter fullscreen mode Exit fullscreen mode

Pointer Operations

To turn a variable into reference, you would need to use the address-of operator (&). Applying the address-of operator to variable y would convert it to a pointer like the example below.

int y = 100;

cout << "Memory Address " << &y << " Value " << y;
//Memory Address 0x7ffe4aa8a4bc Value 100

Enter fullscreen mode Exit fullscreen mode

If you would like to convert a pointer to a regular variable, you need to use the dereference operator (*) like the example below.

int y = 100;
int *x = &y;
cout << "Memory Address " << x  << " Value " << *x;
//Memory Address 0x7fffa5778f94 Value 100

Enter fullscreen mode Exit fullscreen mode

In the example above pointer x points to variable y. The variables hold the same memory address. If the value of x would have change, so does y. Refer to the example below.

int y = 100;
int *x = &y;
*x = 200;
cout << "Value " << y;
//Value 200
Enter fullscreen mode Exit fullscreen mode

Top comments (0)