Pointers
Pointers
PROGRAMMING
LECTURE # POINTERS
1
ADDRESS OF A VARIABLE
Every variable is allocated a memory space large enough
to hold a value of the variable’s data type.
char -> 1 byte
short -> 2 bytes
int -> 4 ..
long -> 4 ..
float -> 4 ..
double -> 8 ..
Each byte of memory has a unique address.
A variable’s address is the address of the first
byte allocated to that variable.
ADDRESS OF A VARIABLE
Suppose the following variables are defined in a
program:
char letter;
short number;
float amount;
Bytes of memory
9.1
Getting the Address of a Variable
GETTING THE ADDRESS OF A VARIABLE
Use address operator & to get address of a variable:
int num = -99;
cout << # // prints address
// in hexadecimal
&num: gives the address of variable num
& is called Address-of-operator
showValues(numbers, SIZE);
SOMETHING LIKE POINTERS : ARRAYS
The values parameter, in the showValues
function, points to the numbers array.
int jellyDonuts;
getOrder(jellyDonuts);
SOMETHING LIKE POINTERS:
REFERENCE VARIABLES
What is valptr + 1?
It means (address in valptr) + (1 * size of an int)
cout << *(valptr+1 * size of an int);
//displays 7
cout << *(valptr+2 * size of an int);
//displays 11
Must use ( ) as shown in the expressions
FROM PROGRAM 9-7
COMPARING POINTERS
Relational operators (<, >=, etc.) can be used to compare
addresses in pointers
9-24
9.7
Pointers as Function Parameters
POINTERS AS FUNCTION PARAMETERS