C++ Pointers and References: Declaration, Usage, Differences & DSA Examples

1. Pointers

Q: What is a pointer in C++?

A pointer is a variable that stores the memory address of another variable. Pointers allow direct memory manipulation, which is crucial for dynamic memory management and data structures like linked lists, trees, and graphs in DSA.

Q: How do you declare and initialize a pointer in C++?

Declaration: Specify the data type of the variable the pointer will point to, followed by *.

Syntax:

type *pointer_name;

Initialization: Assign the address of a variable using the address-of operator (&) or allocate memory dynamically using new.

Example:

int x = 10;
int *ptr = &x; // Points to x
int *ptr2 = new int(20); // Dynamic allocation

Q: How do you access the value pointed to by a pointer?

Use the dereference operator (*) to access the value at the memory address stored in the pointer.

Example: *ptr accesses the value at ptr.

Q: What is a null pointer?

A null pointer points to no valid memory location (set to nullptr in C++11 or later, or NULL in older code). It prevents undefined behavior when a pointer is not yet initialized.

Example:

int *ptr = nullptr;

Q: Can you give an example of pointers in C++?

#include <iostream>
using namespace std;

int main() {
    int x = 10;
    int *ptr = &x; // Pointer to x
    int *ptr2 = new int(20); // Dynamic allocation
    
    // Accessing values
    cout << "Value of x: " << x << endl; // 10
    cout << "Address of x: " << &x << endl;
    cout << "Pointer ptr: " << ptr << endl; // Address of x
    cout << "Value at ptr: " << *ptr << endl; // 10
    
    // Modifying value via pointer
    *ptr = 15;
    cout << "Modified x: " << x << endl; // 15
    
    // Dynamic memory
    cout << "Value at ptr2: " << *ptr2 << endl; // 20
    delete ptr2; // Free memory
    ptr2 = nullptr; // Avoid dangling pointer
    
    // Null pointer check
    if (ptr2 == nullptr) {
        cout << "ptr2 is null" << endl;
    }
    
    return 0;
}

Output:

Value of x: 10
Address of x: [some address]
Pointer ptr: [same address]
Value at ptr: 10
Modified x: 15
Value at ptr2: 20
ptr2 is null

Q: What are common mistakes with pointers?

Q: How are pointers used in DSA?

2. References

Q: What is a reference in C++?

A reference is an alias for an existing variable, allowing direct access and modification without copying. Unlike pointers, references are safer, cannot be null, and don't require dereferencing. They are a C++ feature not available in C.

Q: How do you declare and use a reference in C++?

Declaration: Use & after the type, binding the reference to a variable.

Syntax:

type &ref_name = variable;

Usage: Access or modify ref_name as if it were the original variable.

Note: References must be initialized at declaration and cannot be reassigned to another variable.

Q: What is the difference between pointers and references?

Feature Pointer Reference
Declaration type *ptr; type &ref = var;
Nullability Can be nullptr Cannot be null
Reassignment Can point to different variables Bound to one variable
Dereferencing Requires * No dereferencing needed
Memory Address Stores address Alias, no separate address
Use Case Dynamic memory, arrays, DSA Pass-by-reference, simpler code

Q: Can you give an example of references in C++?

#include <iostream>
using namespace std;

// Function using reference to swap values
void swap(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 5, y = 10;
    
    // Reference declaration
    int &ref = x;
    cout << "x: " << x << ", ref: " << ref << endl; // x: 5, ref: 5
    
    // Modify via reference
    ref = 15;
    cout << "Modified x: " << x << endl; // Modified x: 15
    
    // Pass-by-reference in function
    cout << "Before swap: x = " << x << ", y = " << y << endl;
    swap(x, y);
    cout << "After swap: x = " << x << ", y = " << y << endl; // x: 10, y: 15
    
    return 0;
}

Output:

x: 5, ref: 5
Modified x: 15
Before swap: x = 15, y = 10
After swap: x = 10, y = 15

Q: Can you give a DSA-related example using pointers and references?

Example: Linked list insertion and printing using pointers and references.

#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
    Node(int val) : data(val), next(nullptr) {}
};

// Insert at head using pointer to head reference
void insertAtHead(Node* &head, int val) {
    Node* newNode = new Node(val);
    newNode->next = head;
    head = newNode;
}

// Print list using reference (const pointer)
void printList(const Node* head) {
    while (head != nullptr) {
        cout << head->data << " ";
        head = head->next;
    }
    cout << endl;
}

int main() {
    Node* head = nullptr;
    
    // Insert nodes
    insertAtHead(head, 3);
    insertAtHead(head, 2);
    insertAtHead(head, 1);
    
    // Print list
    cout << "Linked List: ";
    printList(head); // Output: 1 2 3 
    
    // Clean up memory
    while (head != nullptr) {
        Node* temp = head;
        head = head->next;
        delete temp;
    }
    
    return 0;
}

Output:

Linked List: 1 2 3 

Q: How do pointers and references differ from C?

Q: What are best practices for pointers and references in C++?