Basic Pointers

Basic Pointer Program in C++

BeginnerTopic: Memory Management Programs
Back

C++ Basic Pointers Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int num = 10;
    
    // Declare a pointer
    int* ptr;
    
    // Store address of num in pointer
    ptr = &num;
    
    cout << "Value of num: " << num << endl;
    cout << "Address of num: " << &num << endl;
    cout << "Value of ptr (address stored): " << ptr << endl;
    cout << "Address of ptr: " << &ptr << endl;
    cout << "Value pointed by ptr: " << *ptr << endl;
    
    // Modify value using pointer
    *ptr = 20;
    cout << "\nAfter modifying through pointer:" << endl;
    cout << "Value of num: " << num << endl;
    cout << "Value pointed by ptr: " << *ptr << endl;
    
    return 0;
}
Output
Value of num: 10
Address of num: 0x7fff5fbff6ac
Value of ptr (address stored): 0x7fff5fbff6ac
Address of ptr: 0x7fff5fbff6a0
Value pointed by ptr: 10

After modifying through pointer:
Value of num: 20
Value pointed by ptr: 20

Understanding Basic Pointers

A pointer is a variable that stores the memory address of another variable. The & operator gets the address, and the * operator dereferences (accesses the value at the address). Pointers allow indirect access to variables and are fundamental to dynamic memory management in C++.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents