All categories
    CAdvanced

    C Pointers

    Understand pointers in C: read a value through a pointer, modify memory by reference, and swap two variables using pointers.

    01Pointer basics

    main.c
    #include <stdio.h>
    
    int main() {
        int x = 42;
        int *p = &x;
        printf("%d\n", *p);
        return 0;
    }
    Output
    42

    02Modify through a pointer

    main.c
    #include <stdio.h>
    
    int main() {
        int x = 10;
        int *p = &x;
        *p = 99;
        printf("%d\n", x);
        return 0;
    }
    Output
    99

    03Swap with pointers

    main.c
    #include <stdio.h>
    
    void swap(int *a, int *b) {
        int t = *a;
        *a = *b;
        *b = t;
    }
    
    int main() {
        int x = 1, y = 2;
        swap(&x, &y);
        printf("%d %d\n", x, y);
        return 0;
    }
    Output
    2 1