SE250:HTTB:Pointers:Basics
<html>
<image src="http://www.rajithaonline.com/SE250/httb/pointers/final/basics_head.png" width="154" height="92" alt="Basics Header Logo" /> |
</html>
Previous Page | Contents | Next Page |
Basics
A pointer is a variable that holds a memory address. It can be used to "point" to another variable in memory. This is very useful when you have one big data structure in your program and want to manipulate it from other functions. Instead of making copies of this data structure and returning it back, we can use pointers to modify this data structure.
To use a pointer we must declare one. The syntax is like this:
int *pointer;
This declares a pointer to a variable of type "int", and the pointer itself having the name "pointer".
When you declare a pointer like this, C initialises this pointer to a random value. To use a pointer we must first make it point to something useful. Typically you would have a situation like this:
int value; int *pointer; pointer = &value;
The code above makes two variables. One is an "int" type variable, the other is a pointer to a variable of type "int". The third line initialises the pointer with the address of the variable "value". The & operator in C is used to get the address of something. So if we put the & operator in front of the variable "value", C evaluates this to the address of the variable "value" and then assigns that value to the pointer. The diagram below might help to visualise this situation:
<html> <img src="http://www.rajithaonline.com/SE250/httb/pointers/pointer_eg1.png" width="661" height="383" alt="http://www.rajithaonline.com/SE250/httb/pointers/pointer_eg1.png" /> </html>
Syntax
C uses two operators for pointers, * and &
& is the "address" operator. Example: Directs the pointer ptr to point at address of variable number
int *ptr; ptr = &number;
* is the "dereferencing" operator
Example: "dereference" the pointer ptr and sets the value of number to 10
*ptr = 10;
Previous Page | Contents | Next Page |