ITC Lect 17 (Pointers and Strings - I)
ITC Lect 17 (Pointers and Strings - I)
Introduction
• Pointers
– Powerful, but difficult to master
– Simulate call-by-reference
– Close relationship with arrays and strings
Pointer Operators
• & (address operator)
– Returns the address of its operand
– Example
int y = 5;
int *yPtr;
yPtr = &y; // yPtr gets address of y
– yPtr “points to” y
y yptr y
5 500000 600000 600000 5
yPtr
address of y
is value of
yptr
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 17: Pointers and Strings CS 101: Introduction to Computing
Pointer Operators
• * (indirection/dereferencing operator)
– Returns the value of what its operand points to
– *yPtr returns y (because yPtr points to y).
– * can be used to assign a value to a location in memory
*yptr = 7; // changes y to 7
– Dereferenced pointer (operand of *) must be an lvalue (no constants)
• * and & are inverses
– Cancel each other out
*&myVar == myVar
and
&*yPtr == yPtr