C++ Pointers

Pointers are a powerful and fundamental aspect of C++ programming. They allow you to store memory addresses, manipulate memory directly, and pass data between functions. In this article, we will explore the basics of pointers in C++ and how to use them in your programs.

Declaring Pointers

To declare a pointer in C++, you must specify the data type of the data that the pointer will point to, followed by the asterisk * symbol. For example, the following code declares a pointer to an int:

1int *ptr;

The asterisk symbol * tells the compiler that ptr is a pointer and the data type that it will point to is int.

Assigning Address to Pointers

Once a pointer has been declared, you can assign a memory address to it using the address-of operator &. For example, the following code assigns the address of a variable x to the pointer ptr:

1int x = 10; 2int *ptr; 3ptr = &x;

Accessing Data Using Pointers

Once a pointer has been assigned an address, you can access the data stored at that address using the dereference operator *. For example, the following code prints the value of the x variable using the ptr pointer:

1cout << "Value of x = " << *ptr << endl;

Output: Value of x = 10

Passing Pointers to Functions

Pointers can also be passed as arguments to functions. This allows you to pass data between functions and manipulate it in memory. For example, consider the following code that passes a pointer to a function updateValue:

1#include <iostream> 2 3using namespace std; 4 5void updateValue(int *ptr) { 6 *ptr = 20; 7} 8 9int main() { 10 int x = 10; 11 int *ptr = &x; 12 cout << "Value of x before update: " << x << endl; 13 updateValue(ptr); 14 cout << "Value of x after update: " << x << endl; 15 return 0; 16}


1Value of x before update: 10 2Value of x after update: 20

In this example, the updateValue function takes a pointer to an int as an argument and modifies the value of the x variable in memory. This change is reflected in the value of x when we print it after the function call.