DEV Community

chesterchong
chesterchong

Posted on

5 Minutes Introduction to Pointers in C++

Note: This article assumes that you have basic knowledge of programming.

Introduction to Pointer

Every variable is allocated a section of memory big enough to hold a value of the variable's data type. Since every byte of memory has a unique address, a variable's address is then determined by the first byte allocated to that variable. This is where the pointer is introduced to store the memory address of other object or variable.

Declare a variable as usual, but with asterisk added before identifier, indicates a pointer.
int *pointer;

A pointer is a specialised variable to store the memory address of other variable or object of the same data type, except void pointer.

Address of Operator (&)

We can place address operator (&), or ampersand in front of a variable name, or identifier to return the address of the variable.
int variable = 88;
&variable
Then, assign it to a pointer after pointer declaration.
int *ptr;
ptr = &variable;
Afterwards, you can print the memory address of variable to the console.
std::cout << ptr << std::endl;
Finally, the memory address is displayed in the form of hexadecimal numbers.
0x1eed300
You can also print out the address of that pointer.
std::cout << &ptr << std::endl;
The output will be something similar to this.
0x7ffc426d3ec8

Address operator is meant to help you to store and retrieve memory address of a variable.

Dereference Operator (*)

Aside from handling memory address, we can retrieve and modify the data using the pointer that we have declared just now. Simply place an asterisk in front of a pointer to return the value contained in that memory location.
std::cout << *ptr << std::endl;
The output will be the value of which variable was assigned.
88

Dereference operator is used to access and modify data contained in a memory location pointed to by a pointer.

Pointer to Pointer

What's more fun is you can create multi level pointers. The idea is that we create new pointers to store memory address of existing pointers. For instance, you create level 2 pointer.
int **ptr2;
Moving next, you assign it with the memory address of level 1 pointer.
ptr2 = &ptr1;
Lastly, you can choose to print the memory address or the value contained of that variable.
std::cout << *ptr2 << std::endl;
std::cout << **ptr2 << std::endl;
The output:
0x1eed300
88

Pointer Size

The size of a pointer in C++ depends on the word size of processor on most occasions. For instance, pointer size is 4 bytes for a 32 bit computer and 8 bytes for a 64 bit computer, regardless of data types.

Void Pointer

Void pointer is a pointer with no associated data type. It can hold address of any data type and can be typecasted to any data type. For the moment, we ain't going to talk about the implementation of void pointer.

Discussion (0)