# Pointers arithmetic

Basics of the C programming language (20 Part Series)

## Overview

The real power of pointers is when you want to sequence through the elements of an array.
Since each element in an array is an address in memory (that the pointer references), the ++ or -- operators can be used to iterate through an array.
Since the pointers by default reference the first value in an array using standard declaration, e.g. *pMyArray = myArray;, dereferencing the pointer can be used to quickly get the first value *pMyArray, and indirection can be used to access any other elements further in the array using the following syntax:

*(pMyArray + 3);
// accesses the fourth element


The same syntax can be used to assign values to an array. The two expressions below achieve the same result of assigning the number 27 to the 10th element of the array:

myArray = 27;
*(pMyArray + 10) = 27;


To set the pointer to a specific element, it can be done using the 'address of' operator when it is assigned, along with the index desired: *pMyArray = myArray; sets the pointer to the fourth element of the array.

An example of iterating through an array using pointers and summing the elements is below, with explanation in the comments.

int arraySum(int myArray[], const int num)
{
int sum = 0, *ptr;
int * const myArrayEnd = myArray + n;

for (ptr = myArray; ptr < myArrayEnd; ++ptr)
{
// dereference the pointer to get the value and add the value to the sum
sum += *ptr;
}
return sum;
}

int main(void)
{
int arraySum(int myArray[], const int n);
int values = {1, 2, 3, 4, 5};

// here, we are calling the arraySum function with the values array and pointing it to the last element (5)
printf("The sum is %i \n", arraySum(values, 5));

return 0;
}


Functions that process arrays actually use pointers as arguments, so you have a choice between using array notation and pointer notation for array-processing function -- it is a matter of programmer choice.
Like everything in programming, it is a trade-off. Using array notation makes it more obvious that the function is working with arrays, but pointers are closer to machine language and, with some compilers, leads to more efficient code.

Basics of the C programming language (20 Part Series)

Posted on Dec 22 '19 by: ### mikkel250

I've been tinkering with computers since I was a teen. I'm currently pivoting from my current role as Tech Support manager to Full Stack Web Developer. I'm actively seeking employment in the field.

### Discussion   