C Pointers

C pointers are variables that store a memory address instead of a regular value. Pointers are what make C powerful: they let functions change the caller's data, allow dynamic memory, and make arrays and strings work.

Addresses and the & Operator

Every variable lives at an address in memory. & gives that address, and %p prints it (the exact number varies each run).

#include <stdio.h>

int main(void) {
    int score = 50;
    int *p = &score;   // p holds the address of score

    printf("score = %d\n", score);
    printf("*p    = %d\n", *p);   // dereference: read through p
    *p = 75;                      // write through p
    printf("score = %d\n", score);
    return 0;
}
score = 50
*p    = 50
score = 75

Reading Pointer Syntax

  • int *p; declares p as a pointer to int.
  • &x means "the address of x".
  • *p means "the value at the address stored in p" (dereferencing).
  • NULL is a pointer that points to nothing; never dereference it.

Changing Variables with Pointers

Passing addresses lets a function modify the caller's variables. The classic example is swapping two values.

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main(void) {
    int x = 1, y = 2;
    swap(&x, &y);
    printf("x=%d y=%d\n", x, y);
    return 0;
}
x=2 y=1

Pointers and Arrays

An array name converts to a pointer to its first element. Adding 1 to a pointer moves it forward by one element, not one byte. arr[i] is the same as *(arr + i).

#include <stdio.h>

int main(void) {
    int nums[] = {10, 20, 30};
    int *p = nums;
    for (int i = 0; i < 3; i++) {
        printf("%d ", *(p + i));
    }
    printf("\n");
    return 0;
}
10 20 30 

Avoiding Pointer Bugs

  • Initialize pointers, to a valid address or to NULL.
  • Check for NULL before dereferencing a pointer that might be empty.
  • Do not return the address of a local variable; it is destroyed when the function ends.
  • Use const int *p when a function should only read the data.

Frequently asked questions

What is a pointer in C in simple words?

A pointer is a variable that holds the location of another value in memory. It is like writing down a house address instead of carrying the house around.

What is the difference between * and & in C?

& gets the address of a variable. * in a declaration creates a pointer, and * in an expression follows a pointer to the value it points to.

What is a NULL pointer?

A NULL pointer holds a special value meaning "points nowhere". It is used to show that a pointer is empty or that a function failed, such as malloc returning NULL.

Why are pointers considered difficult?

Mistakes like dereferencing invalid addresses cause crashes or silent corruption. With careful initialization and NULL checks, pointers become straightforward.