Pointer Arithmetic

From COMP15212 Wiki

A useful, although rather grubby feature of C, is the ability to perform arithmetic on pointers.

Beware: pointers (addresses) are not numbers, even if C lets you display them in that form; operations like multiplying pointers are meaningless.

Adding a number to a pointer will change the pointer value by that number times the size-of-the-item-pointed-to.

int anIntArray[10];
int *fourthIndex = &( anIntArray[3] );
int *eighthIndex = intPointer + 4;

// Now: eighthIndex == fourthIndex + sizeof(int) * 4;

Example 1: suppose we have a machine with the following properties:

sizeof(int)  == 4			// i.e. 32-bit integers
sizeof(int*) == 8			// i.e. 64-bit address space

int *intPointer;
intPointer = 0x0000000000000100;		// Point at an arbitrary address
intPointer = intPointer + 1;

// Now: intPointer == 0x0000000000000104

Example 2: suppose we have a machine with the following properties:

sizeof(int)  == 8
sizeof(int*) == 8

int *intPointer;
intPointer = 0x0000000000000100;		// Point at an arbitrary address
intPointer = intPointer + 1;

// Now: intPointer == 0x0000000000000108

Experiment (but only if you’re curious) - e.g. with pointers to different types of variables, such as: char, short int, long int, long long int, float, double.

You will probably discover some duplication - results may differ on different machines!

There is an overlap between pointer arithmetic and [Arrays array] access. For example, the two following statements have the same effect:

arr[5]   = 99;
*(arr+5) = 99;

(Refer to a sketch!)

Use and misuse

  • The most useful feature of pointer arithmetic is probably the ability to ‘increment’ to the next element of an array. This is often a feature of moving pointers through strings.
  • The most dangerous feature is probably the ability to get at ‘anything’ in the accessible space. This can cause security problems by introducing bugs (or Trojans?) into code which is allowed privileges – such as device drivers.

Articles on Processes
About this resource • Atomicity • Containers • Context • Context Switching • Daemons • Fork Unix • Hypervisor • Idle • Interprocess Communication • Multi Threading • Mutual exclusion • Pipes • Pointer Arithmetic • Process Control Block (PCB) • Process Priority • Process Scheduling • Process States • Processes • Queues • Queues Extra • Race Conditions • Real Time • Resources • Scheduler • Signal and Wait • Sleep • Starvation • Synchronisation • Thrashing • Threads • Unix Signals