Pointers in C++ – Exploring All Pointer Types (With Examples)

Updated on August 8, 2024

Article Outline

Pointers are a fundamental feature of the C and C++ programming language. It allows direct memory access and  manipulation, enabling dynamic memory allocation. It is very efficient array handling and the implementation of complex data structures. This article explained everything about the Pointers and its types. By understanding the Pointers in C++ language, developers can reach their full potential in creating efficient and powerful applications.

What is a Pointer in C++ Language ?

In C++ language, the pointer is a variable that stores the memory address of another variable. Instead of holding a value directly, a pointer holds the location of where the value is stored in memory. Pointers are very powerful and flexible, but they can also be complex and require careful management to avoid issues like memory leaks and  segmentation faults.

 

The following program demonstrates the pointer in C++ language:

 

Program

#include <iostream> using namespace std; int main() { // Declare an integer variable int num = 10; // Declare a pointer to an integer int* ptr = &num; // Pointer holds the address of num // Output the value of num cout << "Value of num: " << num << endl; // Output the address of num using the pointer cout << "Address of num: " << &num << endl; cout << "Pointer ptr holds address: " << ptr << endl; // Output the value pointed to by ptr cout << "Value pointed to by ptr: " << *ptr << endl; // Modify the value of num using the pointer *ptr = 20; // Output the modified value of num cout << "Modified value of num: " << num << endl; return 0; }

 

Output

Value of num: 10 Address of num: 0x7ffcdb7d96d4 Pointer ptr holds address: 0x7ffcdb7d96d4 Value pointed to by ptr: 10 Modified value of num: 20
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Syntax of Pointers

Pointers in C++ are declared using the following syntax

int *ptr;    // Pointer to an integer char *cptr;  // Pointer to a character

 

We use the asterisk(*) symbol to use  a variable as a pointer in C++ language. The asterisk symbol can be placed anywhere before the pointer name and after the datatype.

 

We can also declare two (or more) pointers together in the same line using the comma (,).  We will need to use the asterisk symbol before each variable name.

 

int* var1, *var2; // Both var1 and var2 are pointers int* var1, var2; // var1 is a pointer, var2 is an integer variable

How to Use Pointers in C++ language?

Let’s see how to use the Pointers variable in C++  language.

  • Create a Pointer variable
  • Assign the address of another variable to the pointer using the & operator.
  • Access the value at the address using the operator.

Symbols Used in Pointers

The following table shows the symbols that are used with pointers.

 

Symbol Name  Description
& Address of operator Used to find the address of variable
* Indirection operator It is used to access the value of an address.

 

The following program demonstrates the pointer:

 

Program

#include <iostream> using namespace std; int main() { // Declare an integer variable int num = 1330; // Declare a pointer to an integer int* ptr = &num; // Pointer holds the address of num // Output the value of num cout << "Value of num: " << num << endl; // Output the address of num using the pointer cout << "Address of num: " << &num << endl; cout << "Pointer ptr holds address: " << ptr << endl; // Output the value pointed to by ptr cout << "Value pointed to by ptr: " << *ptr << endl; // Modify the value of num using the pointer *ptr = 20; // Output the modified value of num cout << "Modified value of num: " << num << endl; return 0; }

 

Output

Value of num: 1330 Address of num: 0x7ffec307e294 Pointer ptr holds address: 0x7ffec307e294 Value pointed to by ptr: 1330 Modified value of num: 20

Pointers and Reference in C++

Pointers and references are powerful features in C++ language that allow developers to manage memory and manipulate data more efficiently. Understanding these concepts is crucial for an effective C++ programming language.

Pointers in C++

Pointers are variables that store memory addresses of other variables. Pointers are used for dynamic memory allocation, arrays, functions and structures. We can also use pointers as an argument in the function.

 

Example of Passing by Pointer

void pointerFunction(int* ptr) { *ptr = 10; }

References in C++

A reference is an alias for another variable. Once a reference is initialized to a variable. It cannot be changed to refer to another variable. References provide an alternative way to access the memory location of variables. We can also pass the argument by reference (call-by-reference with a reference argument) that allows the function to operate directly on the original variables.

 

The following program demonstrates the passing by reference:

void functionByReference(int& ref) { ref = 40; // Directly modifies the original variable }

Comparison and Usage:

  • Call-By-Value: In this technique, A copy of the variable is passed to the function, It does not change the meaning any modification within the function does not affect the original variable. It is very suitable for small types where the overhead of copying is minimal.

 

  • Call By Reference with Pointer Argument: In this technique, the developer passes the memory address of the variable, allowing the function to modify the original variable directly. This technique is very useful with large data structures or for dynamic memory management.

 

  • Call-By-Reference with Reference Argument: This is a very useful technique for modifying the original variable without the syntactic complexity of pointers. This is often preferred for passing objects of user-defined types.

Array Name as a Pointer in C++

When a developer declares an array in C++, the name of the array acts as a constant pointer to the first element of the array. It means, That the array name itself holds the address of the first element. It is very crucial to note that while you can use the array name as a pointer. It cannot modify it like a regular pointer.

 

The following program demonstrates the Array Name as a Pointer in C++:

 

Program

#include <iostream> using namespace std ; int main() { int arr[5] = {10, 20, 30, 40, 50}; // arr is the name of the array, which acts as a pointer to arr[0] std::cout << "Address of the first element: " << arr << std::endl; std::cout << "Address of the first element using &arr[0]: " << &arr[0] << std::endl; std::cout << "First element of the array: " << arr[0] << std::endl; std::cout << "First element of the array using *arr: " << *arr << std::endl; return 0; }

 

Output

Address of the first element: 0x7ffdfc0c8c90 Address of the first element using &arr[0]: 0x7ffdfc0c8c90 First element of the array: 10 First element of the array using *arr: 10

Pointer Arithmetic and Pointer Expressions in C++

We can also perform some arithmetic operations  on pointers in C++ language. These arithmetic operations are:

 

  • Increment Operator(++)
  • Decrement Operator(–)
  • Addition(+)
  • Subtraction(-)

Example 1: Using the Increment Operator

When we use the increment operator(++), The address of the pointer increases. The increase in the address of the pointer is equal to the size of its data type.

 

As we all know all elements stored in the contiguous memory in the array data structure. We can use the increment operator on pointers to access elements in the array.

 

The following program demonstrates the increment operator example in C++:

 

Program

#include <iostream> using namespace std; int main () { int  arr[7] = {10, 20, 30,50,90,30,40}; // storing address of arr in a pointer int  *ptr = arr; for (int i = 0; i < 7; i++) { cout << "Value of var[" << i << "] is: " << *ptr << endl; cout << "Address of var[" << i << "] is: " << ptr << endl << endl; // point to the next location ptr++; } return 0; }

 

Output

Value of var[0] is: 10 Address of var[0] is: 0x7ffd58a35030 Value of var[1] is: 20 Address of var[1] is: 0x7ffd58a35034 Value of var[2] is: 30 Address of var[2] is: 0x7ffd58a35038 Value of var[3] is: 50 Address of var[3] is: 0x7ffd58a3503c Value of var[4] is: 90 Address of var[4] is: 0x7ffd58a35040 Value of var[5] is: 30 Address of var[5] is: 0x7ffd58a35044 Value of var[6] is: 40 Address of var[6] is: 0x7ffd58a35048

In the above program, we used the ptr pointer variable. This pointer is used to access elements of the array arr.

Example 2: Using Decrement Operator

In this section, we will use the decrement operator which (–). This operator is very similar to the increment operator. However, this operator decreases the address of a pointer by the size of its data type.

 

The following program demonstrates the decrement operator:

 

Program

#include <iostream> using namespace std; int main () { int  arr[9] = {13, 233, 343,9343,4,3,1,2,3}; // storing address of last element of arr in a pointer int  *ptr = &arr[8]; for (int i = 2; i >= 0; i--) { cout << "Value of var[" << i << "] is: " << *ptr << endl; cout << "Address of var[" << i << "] is: " << ptr << endl << endl; // point to the previous location ptr--; } return 0; }

 

Output

Value of var[2] is: 3 Address of var[2] is: 0x7ffc83848e90 Value of var[1] is: 2 Address of var[1] is: 0x7ffc83848e8c Value of var[0] is: 1 Address of var[0] is: 0x7ffc83848e88

Example 3: Addition and Subtraction

We can also perform some basic arithmetic operations with pointers like addition and subtraction. Addition is performed using the ‘+’ operator. When a developer performs an addition operator with a pointer then it will point to the next memory address according to the number which is given by the developer. For example, If we add 5 to a pointer variable (ptr+5) , the pointer will point to the memory address located 3 places ahead of the current address.

 

The subtraction is very similar to the addition operator. For example if we subtract 5 from the pointer (ptr -5). Then the pointer will point to the previous memory address.

 

The following program demonstrates the Addition and Subtraction:

 

Program

#include <iostream> using namespace std; int main () { int  arr[8] = {153, 21, 32, 43, 53,99, 503, 499}; int *ptr1, *ptr2; ptr1 = arr; ptr2 = &arr[5]; cout << "Value of ptr1 is: " << ptr1 << endl; cout << "Value of ptr1 + 2 is: " << ptr1 + 2 << endl << endl; cout << "Value of ptr2 is: " << ptr2 << endl; // using subtraction cout << "Value of ptr2 - 1 is: " << ptr2 - 1 << endl << endl; return 0; }

 

Output 

Value of ptr1 is: 0x7fff660a7d10 Value of ptr1 + 2 is: 0x7fff660a7d18 Value of ptr2 is: 0x7fff660a7d24 Value of ptr2 - 1 is: 0x7fff660a7d20

Pointers and String Literals in C++

In C++ language,  String literals are the arrays that contain the null terminated character in the array. Every string literal character is const char type.

 

For Example

const char *name = "Neeraj Kumar ";

The following program demonstrates the String Literal:

 

Program

#include <iostream> int main() { const char* str = "Neeraj Kumar"; std::cout << str << std::endl; return 0; }

 

Output 

Neeraj Kumar

Pointer to Pointer

In C++ language, A pointer variable can store other pointer variable addresses. This is very useful in various situations, such as when dealing with dynamic memory allocation, arrays, and passing pointers to function. To declare a pointer to a pointer, we us one unary operator(*) for each level of chaining of pointers.

 

The following program demonstrates the pointer to pointer:

 

Program

#include <iostream> int main() { int var = 42;     // An integer variable int *ptr = &var;  // A pointer to the integer variable int **ptr2 = &ptr; // A pointer to the pointer // Displaying the values std::cout << "Value of var: " << var << std::endl; std::cout << "Value pointed to by ptr: " << *ptr << std::endl; std::cout << "Value pointed to by ptr2: " << **ptr2 << std::endl; return 0; }

 

Output

Value of var: 42 Value pointed to by ptr: 42 Value pointed to by ptr2: 42

Void Pointer

This is a very special type of pointer in C++ language that can point to any data type. It is declared using the ‘void’ keyword, and it has great versatility in situations where the type of the data is not known at compile time.

 

The following program demonstrates the void pointer:

 

Program

#include <iostream> using namespace std; int main() { int a = 10; float b = 20.5; char c = 'A'; void *ptr; // Pointing to int ptr = &a; cout << "Value of a: " << *(static_cast<int*>(ptr)) << endl; // Pointing to float ptr = &b; cout << "Value of b: " << *(static_cast<float*>(ptr)) << endl; // Pointing to char ptr = &c; cout << "Value of c: " << *(static_cast<char*>(ptr)) << endl; return 0; }

 

Output

Value of a: 10 Value of b: 20.5 Value of c: A

Invalid Pointer

In C++ language, Invalid pointers in C++ are pointers that do not point to a valid memory location. Using invalid pointer can lead to undefined behavior , crashes and security vulnerabilities.

 

The following program demonstrate the Invalid Pointer:

 

Program

#include <iostream> using namespace std; int main(){ int *ptr1;  // invalid pointer because // it does not point to anything int arr[3]; int *ptr2 = &arr[0] + 10; // invalid pointer because // it points to a non-existing address return 0; }

The following example, we created two pointers ptr1 and ptr2. First pointer ptr1 is invalid because this pointer does not point to any address. The pointer two ptr2 is invalid because It points to a non-existing address in the memory.

Null Pointer

In C++ language, we can assign NULL to a pointer variable. In C++ language NULL represents zero value. It is used to indicate that the pointer does not point to any object or function. Using NULL can be efficient, we create valid pointers without storing the variable’s address in the pointer.

 

The following program demonstrates the NULL Pointers in C++ language:

 

Program

#include <iostream> using namespace std; int main () { // defining a null pointer int *ptr = NULL; cout << "The value of ptr: " << ptr; return 0; }

 

Output

The value of ptr: 0

Advantages of Using Pointers

C++ pointers are a powerful feature that offers several advantages. Here are some of the key benefits of using pointers:

 

  • Dynamic Memory Management: Pointers allow dynamic memory allocation, which enables the allocation and deallocation of memory at runtime. It is very crucial for handling variable-sized data structure and efficiently managing resources.

 

  • Effing Array Handling: Pointers can be used to handle arrays efficiently Instead of passing large arrays to functions, You can pass pointers, reducing overhead and improving performance.

 

  • Flexible Data Structures: Pointers are fundamental for implementing complex data structures like linked lists , trees, and graphs. They allow for dynamic and flexible organization of data that can grow and shrink as needed.

 

  • Memory Management: Pointers give control over memory management and optimization. You can allocate, deallocate, and manage memory explicitly, which is useful for performance-critical applications.

Conclusion

Pointers are a fundamental feature in C++ language that provide capabilities for managing and manipulating memory efficiently in the software program. By understanding the various types of pointers and their applications. You can write more efficient, flexible, and powerful  C++ programs. Basic pointers allow you to directly access and manipulate memory addresses, making them essential for tasks such as dynamic memory allocation and function argument passing. By following best practices and employing smart  pointers where appropriate, you can effectively manage memory and optimize your code, ensuring robustness and efficiency in your C++ program.

FAQs
A pointer in C++ is a variable that stores the memory address of another variable. It allows you to directly access and manipulate memory, making it a powerful tool for dynamic memory management and efficient data handling.
A null pointer is a pointer that is initialized to ‘nullptr’ (or ‘NULL’ in older C++ versions) to indicate that it does not currently point to any valid memory location. It helps prevent accidental dereferencing of uninitialized pointers.
A function pointer is a pointer that points to a function. It allows you to call functions dynamically and is useful for implementing callbacks, event handlers, and other scenarios where function behavior needs to be selected at runtime.
Smart pointers are objects that manage the lifetime of dynamically allocated memory automatically. They help prevent common pointer-related issues such as memory leaks automatically. They help prevent common pointer-related issues such as memory leaks and dangling pointers. Common start pointers in C++ include `std::unique str’ and ‘std:weak_ptr’
Pointer syntax is very simple. It place * in front of the name. A pointer is associated with a type. A pointer is associated with a type( such as int and double) too.

Updated on August 8, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved