Pointer Arithmetic

Some consider this a no-no in C++ and generally I’m with them, however its not that hard of a concept and in general not that different from iterators anyway.

#include <stdio.h>


struct foo {
        int a,b,c;
};


struct foo data[10];


int main() {
        /* using ptr arth to find the length */
        struct foo *begin = &data[0];
        struct foo *end = &data[10]; 

        int count = end - begin;
        printf("array count = %d\n", count);

        /* using ptr arth as an iterator */
        struct foo *it = begin;

        while(it != end) {
                static int i = 1;
                printf("%d, ", i);

                i++;
                it++;
        }
        printf("\n");

        return 0;
};

Compile and Run in C

cc ptr_arth.c && ./a.out

Outputs

array count = 10
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,