Pointers and Arrays

Here is a C secret: an array's name works like a pointer to its first item. That's why int arr[] and int *arr mean the same in a function, and why scanf("%s", name) needs no &.

#include <stdio.h>

int main() {
    int nums[3] = {10, 20, 30};
    int *p = nums;           // same as p = &nums[0]
    printf("%d\n", *p);
    printf("%d\n", p[1]);    // a pointer can use [ ] too
    return 0;
}

Output

10
20

Moving a pointer

Adding 1 to a pointer moves it to the next item (not the next byte – C knows how big each item is):

#include <stdio.h>

int main() {
    int nums[4] = {3, 6, 9, 12};
    int *p = nums;
    for (int i = 0; i < 4; i++) {
        printf("%d ", *p);
        p++;
    }
    printf("\n");
    return 0;
}

Output

3 6 9 12 

Walking through a string

The same idea works for strings – stop when you reach '\0':

#include <stdio.h>

int main() {
    char word[20] = "pointer";
    char *c = word;
    int length = 0;
    while (*c != '\0') {
        length++;
        c++;
    }
    printf("%s has %d letters\n", word, length);
    return 0;
}

Output

pointer has 7 letters

Remember: arr[i] and *(arr + i) mean the same thing. Most people find arr[i] easier to read – and that's fine!

Tip: Don't worry if pointers feel strange at first. They confuse everyone at the start. Draw boxes and arrows on paper – it really helps.

HOME LABS COMMUNITY DASHBOARD