C++ Pointers

In C++, a pointer is a variable that holds the memory address of another variable. Instead of directly storing a value, pointers store the location in memory where the value is kept.

Syntax:


type* pointer_name;

Explanation:

  • type is the type of the variable the pointer will point to (e.g., int, char, etc.).
  • pointer_name is the name of the pointer variable.

Use of Pointers

1. Pointer Declaration: A pointer is declared by placing an asterisk (*) before the pointer variable’s name.

Example:


int* ptr;  // Pointer to an integer

2. Pointer Initialization: A pointer is initialized with the memory address of a variable using the address-of operator (&).

Example:


int num = 10;
int* ptr = #  // ptr now stores the address of num

3. Dereferencing: Dereferencing a pointer means accessing the value stored at the memory address the pointer is pointing to. This is done using the asterisk (*).

Example:


int value = *ptr;  // Dereferencing ptr to get the value stored at the address it points to

Complete Example:


#include 
using namespace std;

int main() {
    int num = 10;         // A regular integer variable
    int* ptr = #      // Pointer ptr holds the address of num

    cout << "Value of num: " << num << endl;   // Output: 10
    cout << "Address of num: " << &num << endl;  // Output: Memory address of num
    cout << "Value pointed to by ptr: " << *ptr << endl;  // Output: 10 (value at address ptr points to)

    return 0;
}

Output:

Value of num: 10
Address of num: 0x7ffd9f881344
Value pointed to by ptr: 10

C++ Pointers – Questions and Answers

Q 1: What is a pointer?

Ans: A variable that stores address of another variable.

Q 2: How to declare a pointer?

Ans: int *ptr;

Q 3: What is NULL pointer?

Ans: A pointer pointing to nothing.

Q 4: Why use pointers?

Ans: For dynamic memory and efficiency.

Q 5: What is dereferencing?

Ans: Accessing value using pointer.

C++ Pointers – Objective Questions (MCQs)

Q1. What does a pointer variable store?






Q2. Which operator is used to get the address of a variable?






Q3. Which operator is used to access the value stored at the address of a pointer?






Q4. What is the correct syntax to declare a pointer to an integer?






Q5. Which of the following statements correctly assigns the address of variable x to pointer p?






Related C++ Pointers Topics