In C++ programming language, a pointer is a variable that is also known as a locator or indicator, which points to an address of a value. The symbol of an address is represented by a pointer (*) asterisk symbol. In addition to creating and modifying dynamic data structures, pointers allow programs to match call-by-reference.
One of the main applications of pointers in C++ is to iterate through arrays and other data structures. In C++ , we can declare the pointer variable with the same data type as the array elements and assign the address of the first element. It allows us to direct access and manipulation using pointer arithmetic.
Syntax
It has the following syntax:
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data
In this syntax,
- datatype: It represents the data type that is defined by the pointer.
- var_name: It represents the name that is assigned to the pointer.
Assigning Addresses to Pointers
In C++, the addressof operator (&) is mainly used to store the address of a variable. After that, this address can be assigned to the variable of the pointer to initialize it.
Example:
int num = 45;
int *ptr = #
In this example, ptr represents the pointer that store the address of variable num using the addressof operator (&).
Dereferencing the Pointer
In C++, dereferencing is the process of accessing the value that is stored in the memory address. It is performed using the dereferencing operator. It is represented by the (*) operator.
C++ Pointer Example
Let us take an example to illustrate the pointer in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
int number=45;
int *p;
p = &number; //stores the address of number variable
cout<<"Address of number variable is: "<<&number<<endl;
cout<<"Address of p variable is: "<<p<<endl;
cout<<"Value of p variable is: "<<*p<<endl;
return 0;
}
Output:
Address of number variable is: 0x7ffc7d468acc
Address of p variable is: 0x7ffc7d468acc
Value of p variable is: 45
Explanation:
In this example, we have taken an integer number and a pointer p that is used to store the address of the number. After that, the program accesses using the pointer p and prints the value that is stored at that address.
How to use a pointer in C++?
If we want to create a pointer in C++, we have to follow the following steps.
- First, we have to create a pointer variable.
- After that, we have to use the unary operator (&), which yields the address of the variable, to assign a pointer to a variable's address.
- Using the unary operator (*), which gives the variable's value at the address provided by its argument, we can access the value stored in an address.
Since the data type knows how many bytes the information is held in, we associate it with a reference. The size of the data type to which a pointer points is added when we increment a pointer.
Symbols Used in Pointer
There are commonly two symbols used in C++ pointers.
| Symbol | Name | Description |
|---|---|---|
| & (ampersand sign) | Address operator | Determine the address of a variable. |
| ∗ (asterisk sign) | Indirection operator | Access the value of an address. |
C++ Pointer example to swap two numbers without using a third Variable
Let us take an example to illustrate how we can swap two numbers without using a third variable in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
int a=20, b=10, *p1=&a, *p2=&b;
cout<<"Before swap: *p1="<<*p1<<" *p2="<< *p2<<endl;
*p1=*p1+*p2;
*p2=*p1-*p2;
*p1=*p1-*p2;
cout<<"After swap: *p1="<<*p1<<" *p2="<<*p2<<endl;
return 0;
}
Output:
Before swap: ∗p1=20 ∗p2=10
After swap: ∗p1=10 ∗p2=20
Explanation:
In this example, we swap the values of two integers using pointers and arithmetic operations without a temporary variable. First, we add the values pointed by p1 and p2 and then adjust each to complete the swap. After that, the program shows the values before and after the swap, which demonstrates the pointer manipulation and dereferencing.
Types of Pointers
There are several types of pointers in C++. Some main types of the pointers are as follows:
Null Pointer
In C++, a null pointer is a pointer that is assigned the value nullptr (or NULL) and does nocpp tutorial to any valid location of memory. It is mainly utilized to initialize a pointer when we don't want this NULL pointer to point to any object.
Syntax
It has the following syntax:
int *ptr1 = 0;
int *ptr2 = NULL;
C++ Null Pointer Example
Let us take an example to illustrate the null pointer in C++.
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
// NULL pointer
int *ptr = NULL;
return 0;
}
Void Pointer
In C++, a void pointer is a special type of pointer that can point to any data type. Direct dereference is not possible with void pointers. Before they may be dereferenced, they must be converted into another pointer type thacpp tutorials to a specific data type.
Wild Pointer
In C++, a wild pointer is a pointer that has been initialized and points to some random memory location.
Syntax
It has the following syntax:
int *ptr; // Wild pointer
*ptr = 10; // Undefined behavior
Dangling Pointer
In C++, a dangling pointer is a pointer thacpp tutorials to a deleted (or freed) memory location. It acts as a wild pointer that can cause errors in C++ programs.
Syntax
It has the following syntax:
int *ptr = new int(5);
delete ptr; // ptr is now dangling
Smart Pointer
In C++, smarcpp tutorialers are class templates that the STL provides to manage dynamically allocated memory automatically. It is a wrapper class around the pointer that overloads operators such as * and ->. Smarcpp tutorialers automatically deallocate the memory when the memory is no longer in use, which helps to prevent memory leaks, dangling pointers, and many more.
Pointer to a Pointer
In C++, we can build a pointer to another pointer, which might then point to data or another pointer. The unary operator (*) is needed in the syntax to declare the pointer for each level of indirection.
C++ Pointer to Pointer Example
Let us take an example to illustrate the pointer to pointer in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() { //main function
int num = 18;
// Store the address of var variable
int *ptr1 = #
int **ptr2 = &ptr1;
// Accessing values
cout << *ptr1 << endl;
cout << **ptr2;
return 0;
}
Output:
18
18
What are References and Pointers in C++?
In C++, reference and pointer seem to be similar, but some differences exist between them. A reference is a variable that is another name of the existing variable, while the pointer is a variable that stores the address of another variable.
- Call-By-Value
- Call-By-Reference with a Pointer Argument
- Call-By-Reference with a Reference Argument
Example
#include <iostream>
using namespace std; //using standard namespace
// Pass-by-Value
int square1(int n)
{cout << "address of n1 in square1(): " << &n << "\n";
n *= n;
return n;
}
// Pass-by-Reference with Pointer Arguments
void square2(int* n)
{
cout << "address of n2 in square2(): " << n << "\n";
*n *= *n;
}
// Pass-by-Reference with Reference Arguments
void square3(int& n)
{
cout << "address of n3 in square3(): " << &n << "\n";
n *= n;
}
void example()
{
// Call-by-Value
int n1 = 8;
cout << "address of n1 in main(): " << &n1 << "\n";
cout << "Square of n1: " << square1(n1) << "\n";
cout << "No change in n1: " << n1 << "\n";
// Call-by-Reference with Pointer Arguments
int n2 = 8;
cout << "address of n2 in main(): " << &n2 << "\n";
square2(&n2);
cout << "Square of n2: " << n2 << "\n";
cout << "Change reflected in n2: " << n2 << "\n";
// Call-by-Reference with Reference Arguments
int n3 = 8;
cout << "address of n3 in main(): " << &n3 << "\n";
square3(n3);
cout << "Square of n3: " << n3 << "\n";
cout << "Change reflected in n3: " << n3 << "\n";
}
// Main program
int main() { example(); }
Output:
address of n1 in main(): 0x7ffd90fcf5ec
Square of n1: address of n1 in square1(): 0x7ffd90fcf5cc
64
No change in n1: 8
address of n2 in main(): 0x7ffd90fcf5f0
address of n2 in square2(): 0x7ffd90fcf5f0
Square of n2: 64
Change reflected in n2: 64
address of n3 in main(): 0x7ffd90fcf5f4
address of n3 in square3(): 0x7ffd90fcf5f4
Square of n3: 64
Change reflected in n3: 64
Explanation:
In this example, we compare pass-by-value, pass-by-pointer, and pass-by-reference in C++. It shows that in pass-by-value (square1), several modifications don't affect the original variable. In contrast, both pass-by-pointer (square2) and pass-by-reference (square3) enable the function to change the original value, as shown by matching memory addresses and updated results.
Advantage of pointer
Several advantages of pointer in C++ are as follows:
- Pointer reduces the code and improves the performance, and it is used to retrieve strings, trees, etc. and used with arrays, structures and functions.
- We can return multiple values from a function using a pointer.
- It allows us to access any memory location in the computer's memory.
Usage of pointer
There are many uses of pointers in C++ language. Some of them are as follows:
1) Dynamic memory allocation
In C++ language, we can dynamically allocate memory using malloc and calloc functions where a pointer is used.
2) Arrays, Functions and Structures
Pointers in C++ language are widely used in arrays, functions and structures. It reduces the code and improves the performance.
3) Implementing Data Structure
In C++, pointers can be used to implement complex data structures, including linked lists, trees, and graphs. It allows the elements to be allocated and linked together dynamically.
C++ Pointer FAQs
1) What is a pointer in C++?
In C++, a pointer is a variable that is also known as a locator or indicator, which points to an address of a value. It enables us to direct access and manipulation data that is stored at that address.
2) How do we declare a pointer in C++?
A pointer can be declared using the (*) operator.
Example:
int *ptr
3) What does the & symbol mean in C++?
In C++, the & symbol is utilized to store the variable address.
4) What does it mean by dereferencing a pointer in C++?
In C++, dereferencing is the process of accessing the value stored in the memory address.
For example:
cout << *ptr;
5) What is a NULL pointer in C++?
In C++, a null pointer is a pointer that is assigned the value nullptr (or NULL) and does nocpp tutorial to any valid location of memory.