0
0
C++programming~5 mins

Pointer declaration in C++

Choose your learning style9 modes available
Introduction

Pointers let you store the address of a variable. This helps you work directly with memory locations.

When you want to change a variable inside a function and see the change outside.
When you need to work with arrays or dynamic memory.
When you want to pass large data efficiently without copying.
When you want to create complex data structures like linked lists.
When you want to access hardware or system resources directly.
Syntax
C++
type *pointerName;

The asterisk (*) shows that the variable is a pointer.

The pointer stores the address of a variable of the specified type.

Examples
Declares a pointer p that can hold the address of an int variable.
C++
int *p;
Declares a pointer cptr that can hold the address of a char variable.
C++
char *cptr;
Declares a pointer dptr that can hold the address of a double variable.
C++
double *dptr;
Sample Program

This program shows how to declare a pointer and use it to access the value and address of a variable.

C++
#include <iostream>

int main() {
    int number = 42;
    int *ptr = &number;  // ptr stores the address of number

    std::cout << "Value of number: " << number << "\n";
    std::cout << "Address of number: " << &number << "\n";
    std::cout << "Value stored in ptr (address): " << ptr << "\n";
    std::cout << "Value pointed to by ptr: " << *ptr << "\n";

    return 0;
}
OutputSuccess
Important Notes

The actual address printed will be different each time you run the program.

Use the & operator to get the address of a variable.

Use the * operator to get the value stored at the address the pointer points to.

Summary

Pointers store memory addresses of variables.

Use type *name; to declare a pointer.

Use & to get an address and * to access the value at that address.