Week 11 Pointers
Week 11 Pointers
What is a pointer ?
▪ A pointer is …
o A variable that holds a memory address
o This address is the location of another
object in the memory.
o Pointers as an address indicates where to
find an object
o Not all pointers actually contain an address
o Value of NULL pointer is 0
• Syntax:
type *Variable;
Example:
int *P; /* P is var that can point to an int var */
float *Q; /* Q is a float pointer */
2
char *R; /* R is a char pointer */
What is an address in C ?
▪ Int var = 2;
▪ Var = the actual value of the variable
▪ &var contains the address of the
variable
▪ & is called the reference operator
3
Pointer basics
▪ Variables are allocated at addresses in computer
memory (address depends on computer/operating
system)
▪ Name of the variable is a reference to that memory
address
▪ A pointer variable contains a representation of an
address of another variable (P is a pointer variable in
the following):
4
Reference Operator (&)
VS. Dereference Operator (*)
6
7
Examples
Output: 62FE14
8
Use of Pointers in Functions
▪ Pointer can be used as a function argument
□ Example:
void myFunction (int* p){
*p = 5;
}
▪ When calling a function with a pointer argument, we need
to provide the ADDRESS of the Variable
□ Example:
myFunction(&pr);
□ In this case we say that myFunction() is called by
reference
9
Uses of Pointers in Functions
▪ Pointer can be used as a function argument
□ Example:
void myFunction (int* p){
*p = 5;
}
▪ When calling a function with a pointer argument, we need
to supply ADRESS of Varibale
□ Example:
myFunction(&pr);
□ In this case we say that myFunction() is called by
reference
10
Exercise #1
● Write function that adds up the two numbers where parameters are
passed by reference. The function stores the sum of the two
numbers in the first one.
● Use your function in a loop to scan N integers entered by the user
and accumulate the sum in a variable.
11
Exercise #2
● Write a C function that takes two integers (passed by reference) and swaps their values.
12
Correction #2
13
Pointer Arithmetic
▪ There are ONLY two arithmetic operations that
can be used on pointers : Addition and
Subtraction
▪ This is allows moving between different
memroy zones.
▪ The pointer arithmetic is performed relative to
base type of the pointer.
□ Example:
int* ip = 100;
Then ip + 1 = 104 because the size of int
is 4 bytes 14
Example 1
15
Example 2
16
Example 3
17
Practice Exercise
int i = 12, *ip = &i;
double d = 2.3, *dp = &d;
char ch = 'a', *cp = &ch;
Suppose the address of i, d, and ch are 1000, 2000, and
3000, respectively.
Compute the following:
ip = ip + 1;
ip = ip + 5;
ip = ip – 2;
dp = dp + 3;
cp = cp + 4;
18
Arithmetic Rules
▪ You cannot multiply two pointers
▪ You cannot divide two pointers
▪ You cannot add two pointers
▪ You can only add an integer to a pointer
▪ You can only subtract an integer from a pointer
▪ You can only subtract two pointers of the same data type.
19