0
0
C++programming~5 mins

Pointer and variable relationship in C++

Choose your learning style9 modes available
Introduction

Pointers let you store the address of a variable. This helps you work directly with the variable's location in memory.

When you want to change a variable's value inside a function.
When you need to share a large amount of data without copying it.
When working with dynamic memory to create variables during program run.
When you want to link data structures like lists or trees.
When you want to understand how memory works in your program.
Syntax
C++
type *pointerName = &variableName;

The * means this is a pointer.

The & gets the address of the variable.

Examples
Here, p stores the address of x.
C++
int x = 10;
int *p = &x;
ptr points to the character variable c.
C++
char c = 'A';
char *ptr = &c;
dp holds the address of the double variable d.
C++
double d = 3.14;
double *dp = &d;
Sample Program

This program shows how a pointer stores the address of a variable and how changing the value through the pointer changes the original variable.

C++
#include <iostream>

int main() {
    int num = 42;
    int *ptr = &num;

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

    *ptr = 100; // Change value of num using pointer

    std::cout << "New value of num after change through ptr: " << num << "\n";

    return 0;
}
OutputSuccess
Important Notes

Pointer stores the memory address, not the actual value.

Using *pointer lets you access or change the value at that address.

Always initialize pointers before using them to avoid errors.

Summary

Pointers hold the address of variables.

You can use pointers to read or change the variable's value.

Understanding pointers helps you manage memory and data efficiently.