The Wayback Machine - https://web.archive.org/web/20241126213506/https://www.geeksforgeeks.org/pointers-and-references-in-c/
Open In App

Pointers and References in C++

Last Updated : 11 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable.

Pointers in C++

Pointers in C++ are a symbolic representation of addresses. They enable programs to simulate call-by-reference and create and manipulate dynamic data structures. Pointers store the address of variables or a memory location. 

Syntax

datatype *var_name; 

for example, int *ptr; //ptr points to an address that holds int data.

Example of Pointers in C++

The below program demonstrates the use of pointers in C++.

C++




// C++ program to demonstrate use of pointers in C++;
 
#include <iostream>
using namespace std;
 
int main()
{
    int x = 10; // variable declared
    int* myptr; // pointer variable
 
    // storing address of x in pointer myptr
    myptr = &x;
 
    cout << "Value of x is: ";
    cout << x << endl;
 
    // print the address stored in myptr pointer variable
    cout << "Address stored in myptr is: ";
    cout << myptr << endl;
 
    // printing value of x using pointer myptr
    cout << "Value of x using *myptr is: ";
    cout << *myptr << endl;
 
    return 0;
}


Output

Value of x is: 10
Address stored in myptr is: 0x7ffd2b32c7f4
Value of x using *myptr is: 10

Explanation: The above program declares an integer variable ‘x’ initialized with value 10 and a pointer variable named ‘myptr’. The memory address of x is assigned to myptr. Then it prints the value of x, the address stored in myptr, and the value of x obtained by dereferencing the pointer myptr.

To know more about Pointers, how it works and its mathematical background refer to Pointers in C++.

Application of Pointers in C++

Following are the Applications of Pointers in C++:

  • To pass arguments by reference: Passing by reference serves two purposes
  • For accessing array elements: The Compiler internally uses pointers to access array elements.
  • To return multiple values: For example in returning square and the square root of numbers.
  • Dynamic memory allocation: We can use pointers to dynamically allocate memory. The advantage of dynamically allocated memory is, that it is not deleted until we explicitly delete it.
  • To implement data structures.
  • To do system-level programming where memory addresses are useful.

Features and Use of Pointers in C++

The Pointers have a few important features and uses like it saves memory space, they are used to allocate memory dynamically, it is used for file handling, etc. Pointers store the address of variables or a memory location. 
Example: pointer “ptr” holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through “ptr”.

int *ptr;

‘this’ Pointer in C++

The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name). Even if only one member of each function exists which is used by multiple objects, the compiler supplies an implicit pointer along with the names of the functions as ‘this’. 
Declaration: 

this->x = x; 

References in C++

When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration. There are 3 ways to pass C++ arguments to a function: 

Example of References in C++

The below program demonstrates the use of references in C++.

C++




// C++ Program to demonstrate use of references
 
#include <iostream>
using namespace std;
 
int main()
{
    int y = 10;
 
    // ref is a reference to x.
    int& myref = y;
 
    // changing value of y to 20
    y = 30;
    cout << "value of y is " << y << endl;
    cout << "value of myref after change in value of y is: "
         << myref << '\n';
 
    return 0;
}


Output

value of y is 30
value of myref after change in value of y is: 30

Explanation: The above program demonstrates the use of references. First, it declares an integer variable ‘y’ and then creates reference ‘myref’ which is an alias to y. Changing the value of y also changes the value of myref which can be seen after printing values of both y and myref.

Pointers vs References

Pointers vs References in C++: This article lays the proper ground for differences between Pointer and references. Both references and pointers can be used to change the local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. 
Despite the above similarities, there are the following differences between references and pointers. 

Note A pointer can be declared as void but a reference can never be void.For example:

int a = 10;

void*aa = &a;. //it is valid

void &ar = a; // it is not valid

  • References are less powerful than pointers
  • Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
  • References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
  • A reference must be initialized when declared. There is no such restriction with pointers
  • Passing by pointer Vs Passing by Reference in C++: In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So what should be preferred and why?
  • Passing Reference to a Pointer in C++: In this article let’s compare the usage of a “pointer to pointer” VS “Reference to pointer” in some cases.


Previous Article
Next Article

Similar Reads

lvalues references and rvalues references in C++ with Examples
Prerequisites: lvalue and rvalue in C++, References in C++“l-value” refers to a memory location that identifies an object. "r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the '&' before the name of the variabl
4 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and pointers are very similar as both are used to hav
5 min read
Default Assignment Operator and References in C++
We have discussed assignment operator overloading for dynamically allocated resources here. In this article, we discussed that when we don't write our own assignment operator, the compiler creates an assignment operator itself that does shallow copy and thus causes problems. The difference between shallow copy and deep copy becomes visible when the
2 min read
Can References Refer to Invalid Location in C++?
Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the original variable for the purposes of accessing an
2 min read
Why Can't I Make a Vector of References?
In C++, the Standard Template Library (STL) provides a robust and versatile collection of containers, with std::vector being one of the most commonly used. However, you may encounter an obstacle when trying to create a vector of references. In this article, we are going to look at why you cannot make a vector of references and some ways around it t
4 min read
References in C++
When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration. Also, we can define a reference variable as a type of variable that can act as a reference to another variable. '&' is used for signifying the address of a variable
9 min read
Features and Use of Pointers in C/C++
Pointers store the address of variables or a memory location. Syntax: datatype *var_name; Example: pointer "ptr" holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through "ptr" int *ptr; Features of Pointers: Pointers save memory space.Execution time with pointers is faster beca
2 min read
Difference between Arrays and Pointers
The array and pointers are derived data types that have lots of differences and similarities. In some cases, we can even use pointers in place of an array, and arrays automatically get converted to pointers when passed to a function. So, it is necessary to know about the differences between arrays and pointers to properly utilize them in our progra
7 min read
Difference between Iterators and Pointers in C++ with Examples
In C++ programming, we have both pointers and iterators that are used in managing and manipulating data structures. There are many similarities between iterators and pointers in their ability to reference and dereference memory, but there are certain differences between the two. Understanding the difference is very important in C++ programming. Poi
4 min read
Function Pointers and Callbacks in C++
A callback is a function that is passed as an argument to another function. In C++, we cannot directly use the function name to pass them as a callback. We use function pointers to pass callbacks to other functions, store them in data structures, and invoke them later. In this article, we will discuss how to use function pointer to pass callbacks i
2 min read
Program to reverse an array using pointers
Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer .
4 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read
How many levels of pointers can we have in C/C++
Prerequisite: Pointer in C and C++, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable and the value of a variable can be accessed using dereferencing of the pointer. A pointer is generally initialized as: datatype *variable name; This above declaration i
7 min read
Why do we need reference variables if we have pointers
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do w
4 min read
Unusual behaviour with character pointers
In C++, cout shows different printing behaviour with character pointers/arrays unlike pointers/arrays of other data types. So this article will firstly explain how cout behaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed. Example 1: C/C++ Code // C++ program to illustrate difference
5 min read
C++ Modify Pointers
Prerequisite: Pointer in C++ Pointers are an essential part of the C++ language. It allows us to store the memory address of a variable. One thing to note here is that if we change the value that a pointer is pointing to, then the value of the original variable also changes. Now, let's check the approach we are going to use. Approach: In the below
2 min read
C++ Vector of Pointers
Prerequisites Pointers in C++Vectors in C++ Vector of pointers are vectors that can hold multiple pointers. Each pointer within a vector of pointers points to an address storing a value. We can use the vector of pointers to manage values that are not stored in continuous memory. How to Create Vector of Pointers in C++? Similar to any other vector d
6 min read
Pointers in Containers in C++ STL
Prerequisites: Pointers in C++Container in STL There are different containers in C++ having their own features where if are adding extra functionality of pointer it will contribute in a different way. Although not all of the containers are useful in this context so let's see a few of the containers which can be helpful. There are 5 containers that
5 min read
Passing Pointers to Functions In C++
Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any variable in the function we have to pass the address of
4 min read
What are Wild Pointers? How can we avoid?
Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave unexpectedly. Example of Wild PointersIn the below code, p is a wild pointer. C/C++ Code // C program that demonstrated wild pointers int main() { /* wild pointer */ int* p; /* Some unknown memory locatio
2 min read
Declare a C/C++ function returning pointer to array of integer pointers
Declare "a function with argument of int* which returns pointer to an array of 4 integer pointers". At the first glance it may look complex, we can declare the required function with a series of decomposed statements. 1. We need, a function with argument int *, function(int *) 2. a function with argument int *, returning pointer to (*function(int *
2 min read
Computing Index Using Pointers Returned By STL Functions in C++
Many inbuilt functions in C++ return the pointers to the position in memory which gives an address of the desired number but has no relation with the actual index in a container of the computed value. For example, to find the maximum element in a code, we use std::max_element(), which returns the address in memory, not the index of the desired elem
3 min read
Pointers vs Array in C++
Arrays and pointers are two derived data types in C++ that have a lot in common. In some cases, we can even use pointers in place of arrays. But even though they are so closely related, they are still different entities. In this article, we will study how the arrays and pointers are different from each other in C++. What is an Array?An array is the
3 min read
Program to Reverse a String using Pointers
Given a string, the task is to reverse this String using pointers. Examples: Input: GeeksOutput: skeeGInput: GeeksForGeeksOutput: skeeGroFskeeGApproach: This method involves taking two pointers, one that points at the start of the string and the other at the end of the string. The characters are then reversed one by one with the help of these two p
2 min read
How to Avoid Memory Leaks When Using a Vector of Pointers to Dynamically Allocated Objects in C++?
In C++, managing memory properly is very important to avoid memory leaks, especially when working with dynamically allocated objects. When using a std::vector of pointers to dynamically allocated objects, we need to ensure that all allocated memory is properly deallocated. In this article, we will learn different methods to avoid memory leaks in su
6 min read
C++ Pointers
Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of pointers. The address of the variable you're working with is assigned to the pointer variable that po
9 min read
Smart Pointers in C++
Prerequisite: Pointers in C++ Pointers are used for accessing the resources which are external to the program - like heap memory. So, for accessing the heap memory (if anything is created inside heap memory), pointers are used. When accessing any external resource we just use a copy of the resource. If we make any changes to it, we just change it i
9 min read
Reduce Array and Maximize sum by deleting one occurrence of A[i] and all occurrences of A[i]+1 and A[i]-1
Given an array A[] having N positive integers, the task is to perform the following operations and maximize the sum obtained while reducing the array: Select an array element (say A[i]) and delete one occurrence of that element and add A[i] to the sum.Delete all the occurrences of A[i]-1 and A[i]+1.Perform these operations until the array is empty.
8 min read
Catching Base and Derived Classes as Exceptions in C++ and Java
An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. Let's discuss what is Exception Handling and how we catch base and derived classes as an exception in C++: If both base and derived classes are caught as exceptions, then the catch
4 min read
fesetround() and fegetround() in C++ and their application
fesetround() It sets the specified floating point rounding direction or the "current rounding direction" which is expected to be one of the floating point rounding macros. It is used with rint(), nearbyint() and other rounding functions in C++. Syntax: int fesetround( int round ); where round can be FE_TONEAREST, FE_DOWNWARD, FE_UPWARD, FE_TOWARDZE
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg