C - when to use pointer arithmetic, when to use array indexing?

arrays, c, pointers

Solution

It usually depends on the situation. I don't think there's a rule of thumb.

In some cases, array indexes are better. For example when you have allocated an array

char* ptr = malloc(SIZE);

and you need the value of `ptr` to not change, because you want to free it later, then you can work with indexes.

Or if you get a pointer as a function argument

void func(char* ptr)

and you need to run over the array, then you can increment the pointer itself and you won't need to create a new variable to use as an index.

In most cases however, it depends on your own preferences.

Problem

In C, when is it preferrable to use one over the other?

Original source

Related problems