March 18, 2023

Basics Of Pointers

Posted on March 18, 2023  •  2 minutes  • 359 words

A pointer is a special type of variable that can hold the memory address of an another variable.

Overview of C++ Pointers

1. Accessing address of a variable

We can access the memory address of a variable by & symbol

int x = 10;

&x // gives the memory address

Example

#include <iostream>

int main()
{
    int mark = 300;
    int age = 24;
    int salary = 17000;

    std::cout << "Address of mark: "<< &mark << std::endl;
    std::cout << "Address of age: " << &age << std::endl;
    std::cout << "Address of salary: " << &salary << std::endl;
}

2. Lets talk about Pointers

As we know pointers are the special type of variables that can hold the memory address of a variable.

Syntax

data_type *variableName1;

data_type *variableName2 = &anotherVariableName;

Example


int age = 10; // normal varaible

int *intPtr; // pointer varaible

int *agePtr = &age; // pointer varaible that hold memory address of age

C++ Pointer Overview

3. How to access the value of Pointers

We can use the * (the dereference operator ) to access the value of a pointer.

Example


int age = 10; // normal varaible

int *agePtr;

agePtr = &age; // pointer varaible that hold memory address of age

// To access the value of agePtr we can use *agePtr
std::cout << "Value of agePtr " << *agePtr << std::endl;

4. How to modify the value of Pointers

Here agePtr is pointing to age, that means agePtr is holding the memory address of age variable. So indirectly we can alter the value of age by using agePtr

Example

#include <iostream>

int main() {    
    int age = 10; // normal varaible
    int *agePtr; // pointer varaible
    
    agePtr = &age; // hold memory address of age
    
    // To access the value of agePtr we can use *agePtr
    std::cout << "Value of agePtr " << *agePtr << std::endl;
    
    // Change the value of age by using the agePtr
    *agePtr = 100;
    
    std::cout << "Value of agePtr " << *agePtr << std::endl;
    std::cout << "Value of age " << age << std::endl;

    return 0;
}

Output

Value of agePtr : 10
Value of agePtr : 100
Value of age : 100
Follow me

I work on everything coding and share developer memes