Pointer Arithmetic

Pointers must be declared of a specific data type according to the item they are pointing to:

 

int *myInt ;  //declares a pointer to an int

char *myChar ; //declare a pointer to a char

 

The pointer data type instructs the compiler to allocate the correct amount of memory required for the item being pointed at. This allows arithmetic operations on pointed to objects to be carried out on an individual item of the correct data type size.

 

Arithmetic operations on the pointer are incremented/decremented according to the data type, not a single address location. i.e. the address location is incremented/decremented by the size of the data type. An int would change by 4 Bytes, a char would change by 1 Byte, and so on.

 

The usual example is in relation to an array:

#include <stdio.h>

int main() {

	int myArray[6] = {12, 14, 17, 42, 63, 70} ; //initialise an array
	int *myPtr ; //declare an int pointer
	myPtr = myArray ; //assign array address to pointer

	for (int i = 0; i < 6; i++, myPtr++) { //iterate through the array

		printf("myArray[%d] contents = %d at address location %x \n", i, *myPtr, myPtr) ;

	}
}

*Note: on line 9 the pointer myPtr is being incremented in the iteration of the for loop.

 

Compile & Run:

myArray[0] contents = 12 at address location 22fd40
myArray[1] contents = 14 at address location 22fd44
myArray[2] contents = 17 at address location 22fd48
myArray[3] contents = 42 at address location 22fd4c
myArray[4] contents = 63 at address location 22fd50
myArray[5] contents = 70 at address location 22fd54

 

Notice that the address is being incremented by 4 Bytes for each iteration of myPtr++. This is due to the pointer type being declared as an int pointer, with an requiring 4 Bytes of memory.

 

This time a char pointer is declared and decremented:

#include <stdio.h>

int main() {

	char myArray[7] = {'d', 'e', 'r', 'r', 'i', 'c', 'k'} ; //initialise an array
	char *myPtr ; //declare a pointer
	myPtr = &myArray[6] ; //assign last array element address to pointer

	for (int i = 7; i > 0; i--, myPtr--) { //iterate through the array

		printf("myArray[%d] contents = %c at address location %x \n", i, *myPtr, myPtr) ;

	}
}

Compile & Run:

myArray[7] contents = k at address location 22fd56
myArray[6] contents = c at address location 22fd55
myArray[5] contents = i at address location 22fd54
myArray[4] contents = r at address location 22fd53
myArray[3] contents = r at address location 22fd52
myArray[2] contents = e at address location 22fd51
myArray[1] contents = d at address location 22fd50

 

Notice that each decrement is by 1 Byte, for a char data type.

Leave a Reply