Pointers
- Declaring pointers
- The “&“ operator
- The “*“ operator
- Initialising pointers
- Type mismatches
- Call by reference
- Pointers to pointers
Pointers - Why?
Using pointers allows us to:
— Achieve call by reference (i.e. write functions which change their parameters)
— Handle arrays efficiently
— Handle structures (records) efficiently
— Create linked lists, trees, graphs etc.
— Put data onto the heap
— Create tables of functions for handling Windows events, signals etc.
Already been using pointers with scanf
Care must be taken when using pointers since there are no safety features
Declaring Pointers
- Pointers are declared by using “*”
Declare an integer:
Declare a pointer to an integer:
There is some debate as to the best position of the "*":
Examples Pointer Declaration:
The “&“ Operator
- The “&“, “address of” operator, generates the address of a variable
- All variables have addresses except register variables
Example :
Result :
The “*“ Operator
- The “*“, “points to” operator, finds the value at the end of a pointer
Result :
Here, result will be printed "what "p point to"