Back to series
· 8 min read

Pointers and References


1. What Are Pointers and References?

Both pointers and references can be used to indirectly access a piece of data, but they differ noticeably in semantics, usage, and safety constraints.

1.1 Pointers

A pointer is a variable that stores a memory address. Through a pointer, you can indirectly access the object or memory region at that address.

For example, in C:

int value = 100;
int *ptr = &value;

printf("%d\n", *ptr); // 100

Where:

  • value: an ordinary integer variable that stores the integer 100.
  • &value: the address-of operator, which obtains the memory address of value.
  • ptr: a pointer variable that stores the address of value.
  • *ptr: the dereference operation, which accesses the object pointed to by the pointer.

The pointer itself is also an object. It typically occupies a certain amount of memory, and what it stores is an address value.

1.2 References

A reference is an alias for an existing object. Through a reference, you can access the same object using another name.

For example, in C++:

int value = 100;
int& ref = value;

ref = 200;

std::cout << value; // 200

Where:

  • value: the original object.
  • ref: a reference to value.
  • Modifying ref is actually modifying value.

A reference does not create an independent copy of the data; rather, it provides another way to access an existing object.

1.3 Core Differences

Aspect of Comparison Pointer Reference
Essence An object that stores an address An alias for or reference relationship to an existing object
Whether initialization is required Not necessarily; depends on the language and use case Usually required
Whether null is allowed Null pointers are usually allowed Depends on the language; C++ references are usually not allowed to be null
Whether it can be repointed The pointed-to address can usually be changed C++ references cannot be rebound
Access method Usually requires dereferencing Usually used directly
Arithmetic operations Some pointers in C/C++ support pointer arithmetic Usually not supported
Lifetime The lifetimes of the pointer variable and the pointed-to object are independent of each other The validity of a reference depends on the referenced object
Safety May cause problems such as dangling pointers and out-of-bounds access May also produce dangling references, depending on the language rules

Note that different languages do not define pointers and references in exactly the same way. C++ references, Rust references, and Java object references all differ in their underlying implementation and language constraints.


2. How Pointers Work

2.1 Memory Addresses and Pointer Variables

Computer memory can be abstracted as a series of addressable storage units. A variable typically occupies one or more bytes of memory and has a corresponding address.

Suppose:

int value = 100;
int *ptr = &value;

This can be abstracted as:

Memory containing value:
Address: 0x1000
Content: 100

Memory containing ptr:
Address: 0x2000
Content: 0x1000

Here:

  • The address of value is 0x1000.
  • ptr itself is located at 0x2000.
  • What ptr stores is 0x1000.
  • *ptr accesses the object at address 0x1000.

This shows that the pointer variable itself and the object it points to are two distinct concepts.

2.2 Address-Of and Dereference

The two most important pointer operators in C/C++:

Operator Name Purpose
& Address-of Obtains the address of an object
* Dereference Accesses the target object through a pointer

Example:

int number = 10;

int *ptr = &number;

*ptr = 20;

printf("%d\n", number); // 20

Execution process:

flowchart TB
    A["Create variable number"] --> B["number = 10"]
    B --> C["Get the address of number"]
    C --> D["Pointer ptr stores that address"]
    D --> E["Dereference via *ptr"]
    E --> F["Modify the value of the target object"]
    F --> G["number = 20"]

    style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

2.3 Pointer Types

Pointers have types, and the type determines how the compiler understands the memory that a pointer points to, as well as how it performs access and arithmetic.

int number = 10;
int *int_ptr = &number;

double price = 19.9;
double *double_ptr = &price;

int* and double* are both pointer types, but they point to different data types.

The pointer type affects:

  1. The data type read from or written to when dereferencing.
  2. The step size during pointer arithmetic.
  3. The type checking performed by the compiler.
  4. Alignment requirements on some platforms and in some languages.

For example:

int arr[3] = {10, 20, 30};
int *ptr = arr;

printf("%d\n", *(ptr + 1)); // 20

ptr + 1 does not simply increase the address by 1 byte; it moves forward by the size of one int object.

If sizeof(int) is 4, then the address change is usually 4 bytes.

2.4 Multi-level Indirection with Pointers

A pointer can point to another pointer, forming a multi-level pointer.

int value = 100;

int *ptr = &value;
int **pptr = &ptr;

printf("%d\n", **pptr); // 100

Here:

  • ptr stores the address of value.
  • pptr stores the address of ptr.
  • *pptr gives ptr.
  • **pptr gives value.

Multi-level pointers are often used for:

  • Dynamically creating two-dimensional data structures.
  • Modifying pointer variables inside functions.
  • Manipulating complex structures such as linked lists and trees.
  • Managing resource handles that need to be modified indirectly.

3. How References Work

3.1 A Reference Is an Alias for an Object

In C++, a reference must be bound to an object when it is defined.

int value = 100;
int& ref = value;

ref = 200;

At this point, ref and value provide access to the same object. If the object is modified through either name, the value observed through the other name also changes.

int value = 100;
int& ref = value;

std::cout << value; // 100
std::cout << ref;   // 100

ref = 300;

std::cout << value; // 300

3.2 References Cannot Be Rebound

This is an important difference between C++ references and pointers.

int a = 10;
int b = 20;

int& ref = a;

ref = b;

This code does not make ref refer to b; instead, it assigns the value of b to a.

After execution:

a == 20;
b == 20;

The reference remains bound to a.

If you want to change the object pointed to, use a pointer:

int a = 10;
int b = 20;

int* ptr = &a;
ptr = &b;

Only then does ptr actually change what it points to.

3.3 Syntax Differences Between References and Pointers

int value = 10;

// Pointer
int* ptr = &value;
*ptr = 20;

// Reference
int& ref = value;
ref = 30;

A pointer accesses the target object through dereferencing, while a reference directly uses the object's access syntax.

It should be emphasized: the C++ standard specifies the semantics of references and does not require references to be implemented in the form of pointers. Compilers can optimize the implementation of references according to the specific context; references cannot simply be equated with pointers.


4. Pointers and References in Different Languages

Not all languages provide pointers and references in the same way. Understanding the differences in language design is key to avoiding conceptual confusion across languages.

4.1 C: Pointers at the Core

C provides explicit pointer types and has no reference type in the C++ sense.

void update(int *ptr) {
    if (ptr != NULL) {
        *ptr = 100;
    }
}

int main() {
    int value = 10;

    update(&value);

    return 0;
}

A function accesses the caller's variable through a pointer parameter, thereby achieving indirect modification.

C pointers are highly flexible, but they also require programmers to manage pointer validity and memory access bounds themselves.

4.2 C++: Providing Both Pointers and References

C++ retains C-style pointers and adds reference types.

void updateByPointer(int* ptr) {
    if (ptr != nullptr) {
        *ptr = 100;
    }
}

void updateByReference(int& ref) {
    ref = 200;
}

Both can modify the object passed in by the caller, but they express different constraints:

  • A pointer parameter can be null, and it can also be changed to point elsewhere inside the function.
  • A normal reference parameter must be bound to a valid object and cannot be rebound through the reference itself.

C++ also provides rvalue references, used for move semantics and perfect forwarding:

int&& value = 100;

Rvalue references are different from ordinary lvalue references, and the two must not be confused.

4.3 Rust: Ensuring Memory Safety Through References and Borrowing

Rust combines its reference mechanism with the ownership system and the borrow checker.

fn main() {
    let value = 100;
    let reference = &value;

    println!("{}", reference);
}

In Rust:

  • &T: An immutable reference.
  • &mut T: A mutable reference.
  • References are constrained by lifetime rules.
  • The compiler checks at compile time whether a reference may become invalid.

Rust's core borrowing rules can be summarized as:

  1. Multiple immutable references can exist at the same time.
  2. Within the same scope and time range, a mutable reference cannot coexist with other references.
  3. References must always point to valid data.

For example:

let mut value = 10;

let a = &value;
let b = &value;

println!("{} {}", a, b);

Multiple immutable references can exist at the same time.

However, the following code contains a conflict:

let mut value = 10;

let a = &value;
let b = &mut value;

println!("{}", a);
println!("{}", b);

Here, the immutable borrow and the mutable borrow live at the same time, violating Rust's borrowing rules, so it will not compile.

4.4 Java: Object References Are Not C/C++ Pointers

Java does not expose C/C++-style raw pointer arithmetic to ordinary applications, but object variables hold object references.

class User {
    String name;
}

User user = new User();
user.name = "Alice";

User another = user;
another.name = "Bob";

System.out.println(user.name); // Bob

user and another reference the same object, so when an object property is modified through another, the change can also be observed through user.

However, Java object references cannot perform C/C++-like address arithmetic, nor can they directly dereference arbitrary memory addresses.

In addition, Java method parameters are always passed by value. For object parameters, what is passed is a copy of the reference value:

void update(User user) {
    user.name = "Bob";
}

Inside the method, this reference value can be used to access and modify the original object, but reassigning the parameter does not change the caller's variable itself.

4.5 Python: Variable Binding and Object References

Python variables can be understood as binding relationships between names and objects.

a = [1, 2, 3]
b = a

b.append(4)

print(a)  # [1, 2, 3, 4]

a and b are bound to the same list object, so modifications made to the list through b can also be observed through a.

However, Python does not provide raw memory pointers that ordinary application code can directly manipulate. Its object references are managed by the runtime, and variables themselves are not equivalent to C/C++ pointer variables.

4.6 Comparison of Language Mechanisms

Language Pointer Mechanism Reference Mechanism Main Characteristics
C Native pointers No C++-style references Flexible; memory access safety must be ensured by the programmer
C++ Native pointers Lvalue references, rvalue references Supports both low-level control and high-level abstraction
Rust Raw pointers Borrowed references Lifetimes and borrowing rules impose memory safety constraints
Java Raw pointer arithmetic is not exposed Object references References are managed by the runtime
Python No conventional raw pointers Object references and name binding Dynamic object model; memory is managed by the runtime
Go Provides pointers No C++-style reference types Supports pointer access but restricts pointer arithmetic

5. Memory Safety Issues with Pointers and References

Both pointers and references involve the validity of object access. Even if a language provides reference syntax, it does not mean that all reference operations are inherently safe.

5.1 Null Pointer

A null pointer is a pointer that does not point to a valid object.

C:

int *ptr = NULL;

C++:

int* ptr = nullptr;

Dereferencing a null pointer usually results in undefined behavior and may crash the program.

int* ptr = nullptr;

*ptr = 10; // Error: dereferencing a null pointer

Null pointers are commonly used to represent:

  • An object that has not yet been associated.
  • A lookup operation that produced no result.
  • An optional resource that does not exist.
  • A pointer that currently does not hold a valid target.

Ordinary C++ references do not have corresponding standard null-reference semantics. If an invalid reference is created in an incorrect way, the program's behavior is no longer reliably guaranteed.

5.2 Dangling Pointer

A dangling pointer is a pointer whose pointed-to object has ended its lifetime, but the pointer still retains the original address.

int* create() {
    int value = 100;
    return &value;
}

After the function returns, the lifetime of the local variable value has ended. The returned pointer no longer points to a valid int object.

Using such a pointer results in undefined behavior.

Correct approaches include:

  • Return a value instead of the address of a local variable.
  • Use dynamic allocation and explicitly manage resource lifetimes.
  • Use smart pointers to manage dynamic objects.
  • Ensure the lifetime of the accessed object covers the pointer's usage scope.

5.3 Dangling Reference

A reference can likewise become invalid because the lifetime of the referenced object has ended.

int& create() {
    int value = 100;
    return value;
}