Skip to content
  • Pointer Basics · C

Pointer Basics

LearnViaNotes @learnvianotes· 3 min read

A pointer is a variable that holds the address of another object. & takes an address, * follows one. Pointers are what make C fast, flexible — and dangerous.

Declare, take an address, dereference

C
#include <stdio.h>

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

    printf("x = %d, *p = %d\n", x, *p);
    *p = 20;              /* write through the pointer */
    printf("x = %d\n", x);
    printf("p == &x ? %d\n", p == &x);
    printf("sizeof p = %zu, sizeof *p = %zu\n", sizeof p, sizeof *p);
    return 0;
}
Output
x = 10, *p = 10
x = 20
p == &x ? 1
sizeof p = 8, sizeof *p = 4
ExpressionMeaningValue here
xThe int itself20
&xAddress of x (type int *)e.g. 0x16fdff1ac
pThe address stored in psame as &x
*pThe int at that address20
&pAddress of the pointer variable (type int **)another address

Printing addresses

C — addresses change on every run (ASLR), so no fixed output
#include <stdio.h>

int main(void) {
    int a = 1;
    double d = 2.0;
    printf("&a = %p\n&d = %p\n", (void *)&a, (void *)&d);
    return 0;
}

NULL and pointer states

C
#include <stdio.h>

int find(const int *a, int n, int key, const int **where) {
    for (int i = 0; i < n; i++)
        if (a[i] == key) { *where = &a[i]; return 1; }
    *where = NULL;
    return 0;
}

int main(void) {
    int nums[] = {4, 8, 15};
    const int *hit;
    if (find(nums, 3, 8, &hit)) printf("found %d at index %td\n", *hit, hit - nums);
    if (!find(nums, 3, 99, &hit) && hit == NULL) printf("99 not found, hit is NULL\n");
    return 0;
}
Output
found 8 at index 1
99 not found, hit is NULL

Dereferencing NULL

C — NULL dereference (UBSan: load of null pointer; without it, a segfault)
#include <stdio.h>

int main(void) {
    int *p = NULL;
    printf("%d\n", *p);      /* segmentation fault */
    return 0;
}

What is the size of a pointer?

What is the difference between NULL, 0 and '\0'?

Why use pointers at all?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report