Topic 5: Addresses, Pointers and Arrays
Topic 5: Addresses, Pointers and Arrays
2
Pointers
A pointer is a variable which contains an
address as its value, e.g.
int *p ;
int x = 42;
p= &x;
3
Pointer Variable Declarations and
Initialization
Can declare pointers to any data type
dataType *pVarName;
Pointer initialization
Initialized to 0, NULL, or address
0 or NULL points to nothing
A pointer variable is declared with a type (e.g. int, double, etc) and must
hold the address of a variable of the same type.
It is a syntax error if the type of the pointer does not match the type of the
variable.
E.g. This is wrong:
int *yptr;
double y;
yptr=&y; //error!!
4
Pointer Operators
& (address operator)
Returns memory address of its operand
Example
int y = 5;
int *yPtr;
yPtr = &y; // yPtr gets address of y
yPtr “points to” y
y yptr y
yPtr 5 50000 60000 60000 5
address of
y is value
of yptr
5
Pointer Operators
* (indirection/dereferencing operator)
Returns synonym for object its pointer operand points to
*yPtr returns y (because yPtr points to y).
*yPtr is an alias for y. (i.e. it is another name for y)
6
Examples
1402 A ch1
char ch1=„A‟;
1403 Z ch2
char ch2=„Z‟;
char *p;
7
Examples
1402 B ch1
1403 Z ch2
*p=„B‟;
//contents where p points to
2403 1402 p
8
Examples
1402 B ch1
1403 Z ch2
p=&ch2;
//p takes the address of ch2
2403 1403 p
9
Examples
1402 B ch1
1403 Y ch2
*p=„Y‟;
2403 1403 p
10
Pointer Assignment
int x=40,y=50;
int *xptr, *yptr; //declare two pointers to int
xptr=&x;
yptr=&y; xptr x
40
yptr y
50
11
Pointer Assignment
int x=40,y=50;
int *xptr, *yptr; //declare two pointers to int
xptr=&x;
yptr=&y; xptr x
yptr=xptr; 40
yptr y
50
12
Pointer Assignment
int x=40,y=50;
int *xptr, *yptr; //declare two pointers to int
xptr=&x;
yptr=&y; xptr x
40
yptr y
50
13
Pointer Assignment
int x=40,y=50;
int *xptr, *yptr; //declare two pointers to int
xptr=&x;
yptr=&y; xptr x
*yptr=*xptr; 40
yptr y
40
14
Pointer Expressions and Pointer
Arithmetic
Pointer arithmetic
Increment/decrement pointer (++ or --)
Add/subtract an integer to/from a pointer( + or += , - or -=)
Pointer arithmetic meaningless unless performed on
pointer to array
5 element char array
vPtr points to first element v[ 0 ], which is at location
3000
vPtr = 3000
vPtr++; sets vPtr to 3001
vPtr points to v[ 1 ]
15
Pointer Arithmetic
Arithmetic expressions with pointers to character
data P 1402
(P+1) 1403
(P+2) 1404
(P+1) 1406
16
Array Names as Pointers
17
Array Names as Pointers (ctd’)
int num[6]={2,1,5,8,3,7};
2 1 5 8 3 7
2 1 5 8 3 7
18
Example
char str[4]=“Zen”;
char *p;
p=&str[0]; //or p=str; p Z
p e
n
cout<<*p; \0
//prints Z
cout<<*(p+1);
//prints e, i.e. the contents at the next memory location
//pointed by p
p++;
//moves pointer to the next memory location
cout<<*p;
//prints e
cout<<*p+1;
//adds 1 to the contents of the memory location pointed to by p,
//i.e. adds 1to ASCII of e, so it prints 102.
19
Another Example Output:
#include<iostream> 2 2 2 2
using namespace std; 1 1 1 1
int main() 5 5 5 5
{ 8 8 8 8
int grade[5]={2,1,5,8,3}; 3 3 3 3
int *gPtr = grade; //assign pointer upon declaration. Same as
// gPtr=grade; as separate statement following declaration
int i;
return 0;
}
20
Another Example (continued)
21
Another Example (continued)
Offsets may be included in expressions using
pointers
e.g., *(gPtr + 3) refers to variable three integers
beyond variable pointed to by gPtr
This is the variable grade[3]
Subscripts automatically converted to
equivalent pointer expression by compiler
Parentheses in expression *(gPtr + 3)
necessary to correctly access desired array
element
22
Another Example (continued)
23
Another Example (continued)
24
Example: Counting letters program using pointers
#include <iostream>
//Counts the number of times the letter h appears in
string
using namespace std;
int main()
{
int count=0;
char word[20];
char *p;
25
Counting letters program using pointers
while (*p!='\0')
{
if (*p=='h')
count++;
p++; //move to the next memory location
}
if (count==1)
cout<<"The letter h appears 1 time"<<endl;
else
cout<<"The letter h appears " << count<<"times"<<endl;
return 0;
}
26
The new instruction
Creating new variables at run time, e.g.
int *Numbers ;
Could combine the two statements into:
int i = 0;
Numbers = new int [10]; int *Numbers=new int [10];
while(i<10)
{
cout << "Type in a number:" ;
cin >> Numbers[i] ;
i++;
}
27
A program that uses dynamic storage
#include<iostream>
using namespace std;
int main()
{
int *Numbers ;
int length ;
int i ;
cout<< "How many numbers do you need?";
cin >> length ;
Numbers = new int [length] ;
i=0 ;
cout<<"Please enter "<<length<<" numbers:"<<endl;
while(i<length)
{
cin >> Numbers[i] ;
i++;
}
return 0;
}
28
The delete instruction
29
Using delete with arrays
30
Passing Arguments by Reference with
Pointers
There are three ways to pass arguments
to a function in C++:
1) pass by value
2) pass by reference with reference arguments
3) pass by reference with pointers.
31
Passing Arguments by Reference with
Pointers (ctd’)
Pass-by-reference with pointer arguments
Pass address of argument using & operator
Arrays not passed with & because array name
already pointer (see example function later)
* operator used as alias/nickname for variable
inside of function
32
Example: swap() function with pointer
parameters
#include<iostream>
using namespace std; Function swap() with two pointer
to integer parameters
void swap(int *ptr1, int *ptr2)
{
int temp=*ptr1;
*ptr1=*ptr2;
*ptr2=temp;
}
Calling swap() passing the
addresses of two integers
int main()
{
int num1=30, num2=50;
34
Passing Arrays
When an array is passed to a function, its
address is the only item passed
Address of first location used to store array
Arrays not passed with & because array name already
pointer
35
Passing Arrays (ctd’)
void fun(int list[], int size) void fun(int *list, int size)
36
Example: Passing Arrays
Could also be written as:
int findMax(int *, int)
37
Example: Passing Arrays
Or use:
max=vals[0];
and retain subscript
notation to refer to
individual elements
38
Returning Pointers from Functions
39
A Wrong Way to Return a Pointer
//!!!!WRONG COPY FUNCTION!!!!!!!
#include<iostream>
using namespace std;
int result[6],i;
return result;
}
40
A Wrong Way to Return a Pointer
int main()
{
int grade[6]={2,1,5,8,3,16};
int *p, i;
p=CopyArray(grade, 6);
41
The Correct Way to Return a Pointer
//Corrected COPY FUNCTION!!!!!!!
#include<iostream>
using namespace std;
42
Pointers to Structures
struct Temp{
int num1;
int num2;
}; ptr
num1
num2
Temp *ptr=new Temp;
Data fields can be accessed in two ways:
(*ptr).num1 OR ptr->num1
43
Example: Pointers to Structures
#include<iostream>
using namespace std;
struct Temp{
int num1; t1
int num2; 5 num1
};
int main()
9 num2
{
Temp *t1= new Temp;
(*t1).num1=5; // or t1->num1=5;
(*t1).num2=9; // or t1->num2=9;
cout<<"Num1= "<<(*t1).num1<<" Num2= "<<(*t1).num2<<endl;
// OR cout<<"Num1= "<<t1->num1<<" Num2= "<<t1->num2<<endl;
return 0;
} Output: Num1= 5 Num2= 9
44
Arrays of Pointers
46