Home

Understanding Pointers and Dereferencing

Here is a comprehensive breakdown of the code snippet. It traces exactly how a variable, its memory address, and a pointer interact to modify data in computer memory.

The Annotated Code

#include <stdio.h>

int main(void) {
    // 1. Declare an integer variable and assign it a value
    int number = 10;

    // 2. Declare a pointer variable 'p' and store the address of 'number' inside it
    int *p = &number;

    // 3. Print the integer value normally
    printf("Value of number: %d\n", number);

    // 4. Print the actual memory address where 'number' is stored
    printf("Address of number: %p\n", (void *)&number);

    // 5. Print the address stored inside 'p' (which is the same address)
    printf("Pointer p holds address: %p\n", (void *)p);

    // 6. Use the dereference operator (*) to read the value at that address
    printf("Value through pointer: %d\n", *p);

    // 7. Dereference 'p' to modify the value stored at that address
    *p = 20;

    // 8. Print 'number' again to show it was successfully modified via 'p'
    printf("New value of number: %d\n", number);

    return 0;
}

Sample Terminal Output

When you compile and run this program, your terminal will display output similar to this:

Value of number: 10
Address of number: 0x7ffee3b4a8ac
Pointer p holds address: 0x7ffee3b4a8ac
Value through pointer: 10
New value of number: 20

Note: The actual hexadecimal address (e.g., 0x7ffee3b4a8ac) will change every single time you run the program, as the operating system allocates a different slice of RAM each execution. However, lines 2 and 3 will always match each other.

Step-by-Step Explanation

1. Variables and Memory Allocation

When int number = 10; runs, the computer finds a small slot in its RAM, names it number, and drops the value 10 inside it.

2. The Pointer Setup

The line int *p = &number; creates a new variable p. Instead of holding a regular number, its type is int * (pointer to an integer). The & operator grabs the exact memory address of number and saves it inside p.

3. Reading via Dereferencing

In line 4 of the output, *p is used. The * symbol here is the dereference operator. It tells the computer: “Go to the address stored inside p, look inside that memory slot, and retrieve whatever is there.” It finds 10.

4. Modifying via Dereferencing

The line *p = 20; performs a write operation. It tells the computer: “Go to the address stored inside p, open up that memory slot, and replace whatever is inside with 20.” Because that slot belongs to number, the value of number changes automatically.

Tags: CPointersMemoryProgramming