Course contentsShow
← C
Lesson 455 of 1,2197. PointersFree lesson

Declaring pointer variables with `*`

Declaring pointer variables with *

What you'll learn: How to create a special variable that stores the memory address of another variable instead of a raw value.

The Address Book Analogy

In C, a regular variable is like a box containing a value. For example, an int might contain the number 42. A pointer, however, is like a sticky note that has the address of that box written on it. It doesn't hold the number 42 itself; it tells the computer exactly where in the system's memory that 42 is sitting.

To tell C that a variable is a pointer rather than a normal data container, we use the asterisk symbol (*) during declaration.

How to Declare a Pointer

When you declare a pointer, you must specify what kind of data it is pointing to. A pointer that points to an integer is different from a pointer that points to a decimal (float).

The syntax looks like this: data_type *pointer_name;

#include <stdio.h>

int main() {
    int myAge = 25;       // A regular integer variable
    int *agePointer;      // A pointer variable that can hold the address of an int

    // Note: The * here tells C "this variable is a pointer."
    // It is not currently pointing to anything specific yet.

    float price = 19.99;
    float *pricePointer;  // A pointer specifically for float addresses

    return 0;
}

Where the Asterisk Goes

You might see programmers write int *p;, int* p;, or even int * p;. All three are valid and mean the exact same thing to the C compiler. However, the most common convention is int *p;.

Think of the * as a label that says, "This variable is a map, not the treasure." If you leave the * out, C will think you are trying to store a regular number, which will lead to confusion when you try to navigate to a memory location later.

Why the Data Type Matters

You might wonder why a pointer needs a type like int or char if it’s just storing a memory address. The reason is that different types of data take up different amounts of space. An int usually takes 4 bytes, while a char takes 1. By declaring the pointer as an int *, you are telling C, "The thing at the end of this address is an integer, so look at the next 4 bytes of memory to find the full value."

Key takeaway

A pointer is declared by placing an asterisk (*) between the data type and the variable name, signaling that it will store a memory address rather than a direct value.