CPP Tutorial



C++ POINTERS


Pointers in C++

A pointer is a special variable that stores the memory address of another variable. Pointers are powerful because they allow you to directly access and manipulate memory locations.


Declaring Pointers

To declare a pointer, use the * symbol before the pointer variable name. The pointer must specify the type of data it points to.

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

Assigning Addresses to Pointers

Use the address-of operator & to assign the address of a variable to a pointer.

int num = 42;
int* ptr = #  // ptr now holds the address of num
  

Dereferencing Pointers

The dereference operator * is used to access or modify the value stored at the memory location the pointer points to.

cout << *ptr;  // Outputs: 42

*ptr = 100;       // Changes num to 100
cout << num; // Outputs: 100
  

Pointer Basics Summary

  • A pointer stores the memory address of a variable.
  • Use & to get the address of a variable.
  • Use * to access or modify the value at the pointer’s address.
  • Pointer type must match the data type of the variable it points to.

Example Program

#include <iostream>
using namespace std;

int main() {
    int num = 25;
    int* ptr = #

    cout << "Value of num: " << num << endl;
    cout << "Address of num: " << ptr << endl;
    cout << "Value at address stored in ptr: " << *ptr << endl;

    *ptr = 50;  // modify value using pointer
    cout << "Modified value of num: " << num << endl;

    return 0;
}
  

Important Notes

  • Uninitialized pointers point to unknown memory and can cause errors. Always initialize pointers.
  • Use nullptr (C++11 onwards) to indicate a pointer that points to nothing.
  • Pointers can be used with arrays, functions, and dynamic memory allocation (advanced topics).

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review