← العودة إلى الدورة: C programming from scratch

Pointer arithmetic and its relation to arrays

الفيديو قريبًا

In week 4 you saw that an array passed to a function arrives as an address. It is not a coincidence: in C, arrays and pointers are closely related. In almost every expression, the name of an array automatically becomes a pointer to its first element. This explains why a function receives the address instead of a copy, and opens the door to an alternative way of walking through data: pointer arithmetic.

Adding to a pointer

If p is an int * and you add 1, it does not advance one byte but the size of an int: it moves to the next element. The compiler multiplies by the size of the pointed type. So p + 2 points to the third element, and *(p + 2) reads it. In fact, the notation a[i] is defined as *(a + i). That is why the two traversals in the example are equivalent. Subtracting two pointers of the same array gives the distance in elements, of type ptrdiff_t.

c
#include <stddef.h>
#include <stdio.h>

int main(void) {
    int a[5] = {10, 20, 30, 40, 50};
    int *p = a;                       /* same as &a[0] */

    printf("a[2] = %d, *(a + 2) = %d, *(p + 2) = %d\n", a[2], *(a + 2), *(p + 2));

    for (int i = 0; i < 5; i++) {
        printf("%d ", *(p + i));
    }
    printf("\n");

    int *end = a + 5;                 /* one past the last element */
    for (int *q = a; q < end; q++) {
        printf("%d ", *q);
    }
    printf("\n");

    ptrdiff_t distance = end - a;
    printf("distance = %td elements\n", distance);
    return 0;
}

Pointers may point to any element of the array and also one position past the last, only to compare, but never to dereference it. Any arithmetic that leaves that range is undefined behavior, even if you read nothing. It is the same bounds problem as in the previous week.

Differences between array and pointer

Although they look alike, they are not the same. An array is a block of memory with a fixed size: sizeof(a) gives the total size, and the name a cannot be reassigned. A pointer is a variable that takes the same space as an address and can be reassigned freely. When you pass an array to a function, a parameter declared as int v[] is really an int *v, which is why inside it sizeof(v) gives the size of a pointer and not that of the array.

c
#include <stdio.h>

static void show_size(int v[]) {
    /* v is really an int *, so this is the size of a pointer */
    printf("inside function: sizeof(v) = %zu\n", sizeof(v));
}

int main(void) {
    int a[10] = {0};
    printf("in main: sizeof(a) = %zu\n", sizeof(a));   /* 40 usually */
    show_size(a);

    int b[3] = {1, 2, 3};
    int *p = b;
    p++;                       /* fine: p is a variable */
    /* b++;                    error: b is not assignable */
    printf("*p = %d\n", *p);  /* 2 */
    return 0;
}

Walking strings with pointers

Strings fit naturally with pointers, because the null terminator marks the end without needing to know the length. You can advance a char pointer until you find '\0'. With that idea strlen or a string copy is written in a few lines. But the golden rule still holds: before writing to a destination, make sure it fits.

c
#include <stdio.h>

static size_t my_strlen(const char *s) {
    const char *start = s;
    while (*s != '\0') {
        s++;
    }
    return (size_t)(s - start);
}

static int my_copy(char *dst, size_t dst_size, const char *src) {
    if (dst_size == 0) {
        return 0;
    }
    size_t i = 0;
    while (src[i] != '\0' && i + 1 < dst_size) {
        dst[i] = src[i];
        i++;
    }
    dst[i] = '\0';
    return src[i] == '\0';     /* 1 if everything fitted */
}

int main(void) {
    char small[6];
    printf("length = %zu\n", my_strlen("pointers"));
    int fit = my_copy(small, sizeof(small), "pointers");
    printf("copied \"%s\", fitted = %d\n", small, fit);
    return 0;
}

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →