Адресная арифметика

Простые типы / Указатели

#include <stddef.h>

int numbers[] = {10, 20, 30, 40, 50};

//the name of an array is a pointer to its first element
int *p = numbers;

//+ 2 moves by two elements, not by two bytes
int third = *(p + 2);
//third is 30

p++;
int second = *p;
//second is 20

//in bytes one step is sizeof(int)
ptrdiff_t bytes = (char *)(p + 1) - (char *)p;
//bytes is 4

//the difference of two pointers is a count of elements
int *end = numbers + 5;
ptrdiff_t left = end - p;
//left is 4

//a walk over the array by a pointer;
//end may point just past the last element, but *end is an error
int sum = 0;
for (int *q = numbers; q < end; q++) {
    sum += *q;
}
//sum is 150

printf("third is %d\n", third);
printf("second is %d\n", second);
printf("bytes is %td\n", bytes);
printf("left is %td\n", left);
printf("sum is %d\n", sum);