SE250:HTTB:Pointers:Pointer arithmetic

From Marks Wiki
Revision as of 05:09, 3 November 2008 by Mark (Sọ̀rọ̀ | contribs) (6 revision(s))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

<html>

<image src="http://www.rajithaonline.com/SE250/httb/pointers/final/arithmetic_head.png" width="411" height="92" alt="Pointer Arithmetic Header Logo" />

</html>

Previous Page Contents Next Page



Pointer Arithmetic

Arithmetic Operations that can be performed on pointers include:

  • Incrementing:

Incrementing a pointer increases the value of what the pointer is pointing to by 1. The increment operator is (++).
Eg.

int *x;
int arr[6];
x = &arr[2];
x++;

So x will be pointing to the 3rd element in the array initially, after the increment, it will therefore point to the 4th element in the array.
Note: In the diagram x is the value pointer is pointing at initially and x2 is the value its pointing at post increment.
Ie.
<html> <img src='http://img114.imageshack.us/img114/4522/incptrxd0.png'> </html>

*Just to clarify, incrementing will not increase the value, but the address being pointed to. 
  • Decrementing

Decrementing is the opposite of incrementing, instead of increasing the value of the pointer by 1, it decreases the value by 1. The decrement operator is (--).
Eg.

int *x;
int arr[6];
x = &arr[2];
--x;

So x will be pointing to the 3rd element in the array initially and after decrementing, it will therefore point to the 3rd element in the array. Note: In the diagram x is the value pointer is pointing at initially and x2 is the value it’s pointing at post decrement.
Ie.
<html> <img src='http://img114.imageshack.us/img114/2200/decptrjj5.png'> </html>

  • Addition

You can add an integer to a pointer but you cannot add a pointer to a pointer.
Example:

int *x;
int *y;
int arr[6];
x = &arr[2];
y=x+2;

Here x is pointing to the 3rd element of the array and y will be pointing to the 5th element of the array.
Ie.
<html> <img src='http://img114.imageshack.us/img114/1898/addptrmd5.png'> </html>

  • Subtraction

Pretty much the opposite of addition…
Example:

int *x;
int *y;
int arr[6];
x = &arr[2];
y=x-2;

Here x is pointing to the 3rd element of the array and y will be pointing to the 1st element of the array.
Ie.
<html> <img src='http://img114.imageshack.us/img114/6645/subptrnx2.png'> </html>

Previous Page Contents Next Page