What is a C++ Pointer? A Quick Start Basic Tutorial for Beginners

What are C++ Pointers? A Quick Start Guide for Beginners

1. What is a Pointer? — Starting with “Address”

Imagine you have a room containing your toy (e.g., an integer variable). This room has a unique “door number” (address) in “memory,” like 0x7ffd.... A pointer is like a note with this door number—you can directly find the room (variable) using this note instead of shouting, “Whose toy is in the room?”

In C++, a pointer is essentially a variable that stores not a specific value, but the address of another variable in memory. Just like a note saying “Toy is in Room A,” the note itself occupies memory but points to where the toy is located.

2. Why Use Pointers? — Solving “Direct Memory Manipulation”

Without pointers, you can only modify variables by using their names (e.g., a = 10;). Pointers allow you to directly operate on memory via addresses, which is useful in these scenarios:

  1. Dynamic Memory Allocation: For arrays whose size isn’t known until runtime (e.g., creating an array based on user input length), use new/delete with pointers.
  2. Optimized Function Arguments: When passing large structs or arrays, passing the variable copies the entire data. Passing a pointer only copies the address, improving efficiency.
  3. Direct Array and Memory Access: The array name is essentially the pointer to the first element. Pointers enable more flexible array traversal.

3. Basic Syntax of Pointers — Learn in 4 Steps

1. Declare a Pointer: Specify the “Door Number” Type

Pointers must explicitly target a variable type (e.g., int, double). Syntax:
Type* PointerVariable;
Example:
int* p; (Declares a pointer p targeting int variables)
double* q; (Declares a pointer q targeting double variables)

Note: * marks the pointer type, not multiplication!

2. Get the Address: “Attach the Door Number” to the Pointer

To make a pointer target a variable, use the address-of operator & to get the variable’s address:
PointerVariable = &VariableName;
Example:
int a = 10;
int* p = &a; (Now p points to a’s address)

3. Dereference: “Find the Toy in the Room” via the Pointer

To access the value of the variable targeted by the pointer, use the dereference operator *:
*PointerVariable refers to “the variable pointed to by the pointer.”
Example:
cout << *p; (Outputs the value of a, which is 10)

4. Modify the Value: “Modify the Toy” via the Pointer

Use dereferencing to directly change the value of the variable pointed to by the pointer:
*PointerVariable = NewValue;
Example:
*p = 20; (Modifies a’s value to 20 indirectly)

4. Practical Example — How Pointers Work in Code

#include <iostream>
using namespace std;

int main() {
    // 1. Define a regular variable
    int a = 10;
    cout << "Value of variable a: " << a << endl;  // Output: 10

    // 2. Declare and initialize a pointer to point to a
    int* p = &a;  // &a gets a's address, assigned to p

    // 3. Print the pointer's stored address (a's address)
    cout << "Address stored in pointer p: " << p << endl;  // e.g., 0x7ffd... (random address)

    // 4. Access a's value via dereferencing p
    cout << "Value obtained by dereferencing p: " << *p << endl;  // Output: 10

    // 5. Modify a's value via the pointer
    *p = 20;
    cout << "Value of a after modification: " << a << endl;  // Output: 20 (a is modified indirectly by p)

    return 0;
}

5. Important Notes — Avoid These Pitfalls!

1. Pointers Must Point to Valid Addresses

If a pointer is uninitialized (no valid variable target), dereferencing it causes a “dangling pointer,” which may crash the program.

Bad Example:
int* p; // p is uninitialized, pointing to an unknown address
*p = 10; // Dangerous! Modifies unknown memory, may cause errors

Good Practice:
int a = 10;
int* p = &a; // p must first target an existing variable

2. Pointer Types Must Match

Pointers can only target variables of their declared type. For example:
double d = 3.14;
int* p = &d; // Error! Only double* can target double variables

3. Null Pointers: Temporarily No Target

If a pointer isn’t needed to target a variable yet, assign it nullptr (C++11 standard) to indicate “no target.”

int* p = nullptr; // p temporarily points to nothing
Never dereference a null pointer; it will crash the program.

6. Pointers and Arrays — The Array Name is a Pointer to the First Element

The array name (e.g., arr) is essentially the address of the first element. Pointers can directly access array elements:

int arr[3] = {1, 2, 3};
int* p = arr; // p is equivalent to &arr[0] (address of the first element)

// Traverse the array via the pointer
for (int i = 0; i < 3; i++) {
    cout << p[i] << " "; // Equivalent to arr[i]
}
// Output: 1 2 3

7. Summary

Pointers are a core C++ concept, where they act as “variables storing memory addresses.” Key takeaways:
- Address: A unique memory location for variables.
- Dereferencing: Use * to access the value at the pointer’s address.
- Avoid Dangling Pointers: Always initialize pointers to valid variables.

Pointers may seem abstract at first, but with practice (e.g., modifying variables via pointers, traversing arrays), you’ll master them quickly. Remember: Pointers are the “key” to flexible memory manipulation in C++, but always ensure address validity!

Exercise: Define a variable b = 50, use a pointer q to target it, modify b to 100 via q, and print b.

(Note: This tutorial covers only single-level pointers. Advanced topics like multi-level pointers and pointer arrays can be learned later.)

Xiaoye