C Pointers

A pointer is a variable that stores the memory address of another variable. Instead of holding a value like 10 or 'A', it holds the location where that value lives. Pointers are one of the most powerful features of C, and understanding them unlocks arrays, strings, dynamic memory, and much more.

What is a pointer?

Every variable you create in C is stored somewhere in memory, and that spot has a numeric address. A pointer simply remembers that address. You can think of a normal variable as a house and a pointer as a piece of paper with the house's address written on it.

Two operators do most of the work. The address-of operator & gives you the address of a variable, and the dereference operator * lets you read or change the value stored at an address.

Creating and using a pointer

#include <stdio.h>

int main() {
    int age = 30;
    int *ptr = &age;   // ptr stores the address of age

    printf("Value of age: %d\n", age);
    printf("Address of age: %p\n", &age);
    printf("Value via pointer: %d\n", *ptr);

    return 0;
}

Here int *ptr declares a pointer to an int. We assign it &age so it points at our variable. Writing *ptr then reads back through the pointer to find 30. The %p format specifier is used to print an address.

Changing a value through a pointer

Because a pointer knows where a variable lives, you can update the original variable by writing to the dereferenced pointer. This is the idea behind passing data into functions so they can modify it.

Modifying through a pointer

#include <stdio.h>

int main() {
    int score = 50;
    int *p = &score;

    *p = 95;   // write a new value at score's address

    printf("Score is now %d\n", score);  // prints 95
    return 0;
}
SymbolNameWhat it does
*DeclarationMarks a variable as a pointer, e.g. int *p
&Address-ofReturns the memory address of a variable
*DereferenceReads or writes the value stored at an address
Note: A pointer that is declared but not pointed at anything valid contains garbage. Reading or writing through it causes undefined behavior. Set unused pointers to NULL and check before dereferencing.

Exercise: C Pointers

In the declaration `int *p;`, what does the `*` actually mean?