Course contentsShow
← C
Lesson 692 of 1,21910. Input and OutputFree lesson

How scanf uses memory addresses

How scanf uses memory addresses

What you'll learn: Why you must use the ampersand symbol to give scanf the specific location where your data should be stored.

The Mailbox Analogy

Imagine you are expecting a package. If you tell the delivery driver, "The package is a blue shirt," they can’t do much with that information. They don't need to know what is inside the box yet; they need to know your home address so they can physically put the box inside your mailbox.

In C, the scanf function is like that delivery driver. When you want to get a value from the user, you can't just give scanf the name of a variable. If you do, C simply hands over the current value stored in that variable. Instead, you must provide the memory address—the specific "house number" in your computer's RAM—where scanf should drop off the new data.

Using the Ampersand (&)

To get the address of a variable, we use the address-of operator, which is the ampersand symbol (&). Think of & as the "Address Locator." When you put it in front of a variable name, you aren't sending the data; you are sending a pointer to the storage bin itself.

#include <stdio.h>

int main() {
    int userAge;

    printf("Enter your age: ");
    
    // We use &userAge to tell scanf WHERE to put the number.
    // Without the &, scanf wouldn't know which memory slot to update.
    scanf("%d", &userAge);

    printf("You are %d years old.\n", userAge);
    
    return 0;
}

Why this matters for safety

If you forget the &, scanf will take whatever random value happens to be inside userAge and treat that value as a memory address. This usually causes the program to crash (a "segmentation fault") because the program tries to write data to a restricted or non-existent part of the computer's memory. By providing the explicit address, you ensure that the input flows safely into the exact container you’ve reserved for it.

Key takeaway

Use the & operator with scanf to pass a variable's memory address, allowing the function to reach into your computer's storage and update the value directly.