Page 68 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 68
Unit 5: Pointers
Notes
Did u know? A pointer to any variable type is an address in memory — which is an integer
address. A pointer is definitely NOT an integer.
The reason we associate a pointer to a data type is so that it knows how many bytes the data is
stored in. When we increment a pointer we increase the pointer by one “block” memory.
So for a character pointer ++ch_ptr adds 1 byte to the address.
For an integer or float ++ip or ++flp adds 4 bytes to the address.
Consider a float variable (fl) and a pointer to a float (flp) as shown in Figure 5.2.
Figure 5.2: Pointer Arithmetic
1 float (4 bytes)
fl
flp ++flp flp + 2
p
Source: http://www.cs.cf.ac.uk/Dave/C/node10.html
Assume that flp points to fl then if we increment the pointer ( ++flp) it moves to the position
shown 4 bytes on. If on the other hand we added 2 to the pointer then it moves 2 float positions
i.e 8 bytes as shown in the Figure.
Task Compare and contrast & operator and dereference operator.
5.1.1 Pointer and Functions
Let us now examine the close relationship between pointers and functions.
When C passes arguments to functions it passes them by value.
There are many cases when we may want to alter a passed argument in the function and receive
the new value back once to function has finished. Other languages do this (e.g. var parameters in
PASCAL). C uses pointers explicitly to do this. Other languages mask the fact that pointers also
underpin the implementation of this.
The best way to study this is to look at an example where we must be able to receive changed
parameters.
Let us try and write a function to swap variables around.
The usual function call:
swap(a, b) WON’T WORK.
Pointers provide the solution: Pass the address of the variables to the functions and access
address of function.
LOVELY PROFESSIONAL UNIVERSITY 61