Month End Sale: Get Extra 10% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Pointers in C++: Declaration, Initialization and Advantages

Pointers in C++: Declaration, Initialization and Advantages

01 Jul 2024
Intermediate
6.47K Views
23 min read
Learn via Video Course & by Doing Hands-on Labs

Free C++ Course Online with Certificate [Full Course]

Pointers in C++

Pointers in C++ point to the memory location of another variable. They let us access any location in the computer's memory, acting as variables.

In this comprehensive C++ tutorial, we'll take you on a guided tour of pointers in C++, their uses, declaration, initialization, and types of pointers, as well as modify the values of pointers. In addition to the insights shared in this article, consider taking advantage of C++ Online Training to enhance your knowledge and proficiency.

What are Pointers in C++?

Pointers are variables that contain the memory address of another variable instead of a direct value. Such variables can be of type. int, float, char, etc. By referencing this memory address, programmers can access and modify data indirectly.

What are Pointers in C++

Use of Pointers in C++

  • Dynamic memory allocation - In the C++ programming language, the programmers can dynamically allocate memory by using the malloc() and calloc() functions, mainly where the pointer is used. This is the primary use of pointers in C++.
  • Arrays, Functions, and Structures - Pointers in the c ++ programming language are widely used in arrays, structures, and functions. It reduces the code and improves the performance of that particular program.

Pointer Declaration in C++

We do not initialize the pointer; we declare it using the * (asterisk symbol) before a pointer's name or after the data type. This asterisk sign acts as the ticket to enter the address of the variables. If a pointer has an asterisk with it, it will show the value of the variable.

Syntax

  • datatype *var_name;
  • datatype* var_name; //preferred syntax
    

Example

  • int *a;//pointer to int 
  • int* a;//pointer to int 

Read More - C++ Interview Interview Questions and Answers

Pointer Initialization in C++

The procedure of initializing a pointer is where we give the memory address of another variable using the & (address of) operator.

Example

#include <iostream>
using namespace std;

int main() {
 int x = 42; // Declare and initialize an integer variable 'x'
 
 // declare pointer variable 'ptr' and initialize it with the address of 'x'
 int *ptr = &x; 

 // print value of x
 cout << "x = " << x << endl;
 
 // print address of x
 cout << "Address of x (&x) = " << &x << endl
 << endl;

 // print pointer ptr
 cout << "ptr = " << ptr << endl;

 // print the content of the address ptr points to
 cout << "Content of the address pointed to by ptr (*ptr) = " << *ptr << endl;
 
 return 0;
}

In this C++ code,

  • an integer variable, x is initialized to 42
  • a pointer, ptr is created to hold x's address in memory.

Output

x = 42
Address of x (&x) = 0x7ffeb5f7b3c4

ptr = 0x7ffeb5f7b3c4
Content of the address pointed to by ptr (*ptr) = 42

* used in the above example can confuse you. It serves two purposes:

  • When used in the declaration (int *a), it creates a pointer variable.
  • When not used in the declaration (*a), it acts as a dereference operator.

Modifying Values Pointed by Pointers

Example

 #include <iostream>
using namespace std;

int main() {
 int x = 42; // Declare and initialize an integer variable 'x'
 
 // declare pointer variable 'ptr' and initialize it with the address of 'x'
 int *ptr = &x; 

 // print value of x
 cout << "x = " << x << endl;

 // print *ptr
 cout << "*ptr = " << *tr << endl
 << endl;

 cout << "Changing value of x to 70:" << endl;

 // change value of x to 70
 x = 70;

 // print x
 cout << "x = " << x << endl;

 // print *ptr
 cout << "*ptr = " << *ptr << endl
 << endl;

 cout << "Changing value of *ptr to 60:" << endl;

 // change value of ptr to 60
 *ptr = 60;

 // print x
 cout << "x = " << x << endl;

 // print *ptr
 cout << "*ptr = " << *ptr << endl;
 return 0;
}

In the above C++ code in C++ Compiler, ptr points to the address of x. Therefore

  • when value of x is changed, *ptr also gets changed
  • when *ptr is modified, value of x also gets modified

Output

x = 42
*ptr = 42

Changing value of x to 70:
x = 70
*ptr = 70

Changing value of *ptr to 60:
x = 60
*ptr = 60

Read more: Call by Value and Call by Reference in C++

Types of Pointers in C++

1. NULL Pointer

A NULL pointer indicates that it has not been initialized and points to nowhere in memory.

Syntax

int* nullPointer = NULL;

Example of NULL Pointers in C++ Online Editor


#include <iostream>
using namespace std;

int main() {
    int *ptr = nullptr; 
    if (ptr == nullptr) {
      cout << "This pointer is called the null pointer." << endl;
    }

    return 0;
}
 

Output

This pointer is called the null pointer. 

2. Integer Pointers

The memory location of an integer variable is stored in integer pointers.

Syntax

int* intPointer;

Example of Integer Pointers in C++


#include <iostream>

int main() {
    // Declare an integer variable
    int num = 42;

    // Declare an integer pointer and initialize it with the address of the variable
    int *ptr = #

    // Access the value using the pointer
    std::cout << "Value of num: " << *ptr << std::endl;

    // Modify the value using the pointer
    *ptr = 100;

    // Display the modified value
    std::cout << "Modified value of num: " << num << std::endl;

    return 0;
} 

Output

Value of num: 42
Modified value of num: 100

3. Array Pointer

The initial element of an array may be referenced by array pointers. It is applicable for random access of the array elements by using the pointer instead of the array indices. A pointer not only stores the memory address of the first element of an array but is also associated with the element type of the array. This means that the pointer "knows" the type of data it points to, enabling it to access and manipulate the array elements correctly.

Syntax

int arr[5];
int* arrPointer = arr;

Example of Array Pointers in C++


#include <iostream>
int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int* p = arr; // Array pointer to the first element of arr

    for (int i = 0; i < 5; i++) {
        std::cout << *(p + i) << " ";  // Accessing array elements through pointer arithmetic
    }

    std::cout << std::endl;  

    return 0;
}

Output

10 20 30 40 50 

4. Function Pointers

You can call functions indirectly by using function pointers that save the address of a function.

Syntax

int (*funcPointer)(int, int);

Example of Function Pointers in C++


#include <iostream>

// Define two functions with the same signature
int add(int a, int b) {
    return a + b;
}

int subtract(int a, int b) {
    return a - b;
}

int main() {
    // Declare a function pointer with the same signature as the functions
    int (*operation)(int, int);

    // Initialize the function pointer with the address of the add function
    operation = add;

    // Use the function pointer to call the add function
    int result = operation(10, 5);
    std::cout << "Result of addition: " << result << std::endl;

    // Reassign the function pointer to the subtract function
    operation = subtract;

    // Use the function pointer to call the subtract function
    result = operation(10, 5);
    std::cout << "Result of subtraction: " << result << std::endl;

    return 0;
}

Output

Result of addition: 15
Result of subtraction: 5

5. void Pointer

Void pointers can point to any data and can be typecasted to any type. It doesn’t have an associated data type. It can hold the address of a data type of integer, a float, or a string.

Syntax


void* voidPointer;

Example of void Pointers in C++


#include <iostream>
using namespace std;

int main() {
    int x = 105;
    float y = 89;
    void *p = nullptr;  

    p = &x;
    cout << "Integer value: " << *(static_cast(p)) << endl;  
    p = &y;
    cout << "Float value: " << *(static_cast(p)) << endl;

    return 0;
}

Output

Integer value: 105
Float value: 89

6. Structure Pointer

A structure pointer points to the address of a structure. Pointers to structures help in dynamic memory allocation, passing function parameters to big structures with less overhead and data structures, such as linked lists and trees.

Syntax


struct MyStruct {
 int data;
};
struct MyStruct* structPointer;

Example of Structure Pointer in C++ Online Compiler


#include <iostream>

#include <cstring>
using namespace std;

struct Employee {
    int id;
    char name[20];
};

int main() {
    Employee *ptr = new Employee;  // Dynamically allocate memory for one Employee struct

    // Access struct members through pointer
    ptr->id = 789;
    strcpy(ptr->name, "Sourav Kumar");

    cout << "Employee ID: " << ptr->id << endl;
    cout << "Employee Name: " << ptr->name << endl;

    delete ptr;  
    return 0;
}

Output

Employee ID: 789
Employee Name: Sourav Kumar

7. Double Pointers

Double pointers are pointers to pointers, i.e., they point to the memory address of another pointer and are frequently employed in linked lists or multi-dimensional arrays.

Syntax


int** ptr;  // Declaration of a double pointer to an integer

Example of pointer to pointer in C++


#include <iostream>

int main() {
    int value = 50;
    int* singlePtr = &value;  // Pointer to an integer
    int** doublePtr = &singlePtr;  // Double pointer to an integer pointer

    std::cout << "Value: " << value << std::endl;
    std::cout << "Single pointer points to value: " << *singlePtr << std::endl;
    std::cout << "Double pointer points to single pointer: " << **doublePtr << std::endl;

    return 0;
}

Output

Value: 50
Single pointer points to value: 50
Double pointer points to single pointer: 50

Advantages of using Pointers in C ++

There are a few advantages to using pointers in C ++

  • Pointers help to reduce the code and improve the performance of the program. It mainly assists in retrieving trees, strings, and many more. Pointers are primarily used with arrays, functions, and structures.
  • The programmer or user can return multiple values from a particular function with the help of the pointer
  • Pointers help users access any memory location in the computer's memory.

Summary

Pointers are a powerful tool in C++, but they can be challenging to use correctly. If you're new to pointers, start by reading this C++ Certification Training guide and experimenting with them in your programs. Your ability to code for practical and feature-rich programs will improve as a result of understanding C++ pointers and practicing with examples.

FAQs

Q1. What are references and pointers?

Pointers are variables that contain the memory address of another variable instead of a direct value. A reference is an alias for another variable that allows direct access without explicitly using memory addresses.

Q2. How do you declare and initialize a pointer in C++?

In C++, you declare and initialize a pointer by specifying the type of data it will point to, followed by an asterisk (*), the pointer's name, and then assigning it the address of a variable using the address-of operator (&). For example: int value = 42;
int* ptr = &value; 

Q3. What is pointer arithmetic and how does it work in C++?

Pointer arithmetic in C++ involves operations like addition or subtraction on pointers to navigate through elements in an array. It works by adjusting the pointer's address based on the size of the data type it points to, ensuring proper alignment.

Q4. How do you use pointers with dynamic memory allocation in C++?

In C++, you use the new keyword to allocate dynamic memory and obtain a pointer to it. For example:
int* ptr = new int; // Allocates memory for int and returns a pointer to it 
delete ptr; // Frees the allocated memory
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Software Architecture and Design Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Azure Developer Certification Training Jul 28 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Data Structures and Algorithms Training with C# Jul 28 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Microsoft Azure Cloud Architect Aug 11 SAT, SUN
Filling Fast
03:00PM to 05:00PM (IST)
Get Details
Angular Certification Course Aug 11 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this