0% found this document useful (0 votes)
47 views46 pages

Topic 5: Addresses, Pointers and Arrays

Pointers allow variables to store memory addresses rather than values directly. The document discusses pointers, pointer operators like & and *, pointer arithmetic, arrays as pointers, and dynamic memory allocation using new. Examples are provided to demonstrate pointers to variables, arrays treated as pointers, pointer expressions and arithmetic, and using pointers to count letters in a string.

Uploaded by

Pierre Salfiti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views46 pages

Topic 5: Addresses, Pointers and Arrays

Pointers allow variables to store memory addresses rather than values directly. The document discusses pointers, pointer operators like & and *, pointer arithmetic, arrays as pointers, and dynamic memory allocation using new. Examples are provided to demonstrate pointers to variables, arrays treated as pointers, pointer expressions and arithmetic, and using pointers to count letters in a string.

Uploaded by

Pierre Salfiti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Topic 5

Addresses, Pointers and Arrays


Objectives
(Chapter 11 in textbook)

You should be able to describe:

 Addresses and Pointers


 Pointer Operators
 Pointer Arithmetic
 Array Names as Pointers
 Dynamic Memory Allocation
 Passing Arguments by Reference with Pointers
 Passing Arrays
 Returning Pointers from functions
 Pointers to structures

2
Pointers
 A pointer is a variable which contains an
address as its value, e.g.
int *p ;
int x = 42;
p= &x;

Variable Address Value


name
p 20500 20566
X 20566 42

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)

 Dereferencing a pointer means to obtain the contents (i.e.


the value) to which the pointer is pointing to
 cout<<*yptr;

//will print 5, based on previous slide


 *yptr = 9;
// assigns 9 to y

6
Examples
1402 A ch1
char ch1=„A‟;
1403 Z ch2
char ch2=„Z‟;
char *p;

p=&ch1; //p takes address of ch1 2403 1402 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

 Arithmetic expressions with pointers to integer


data 1402
P

(P+1) 1406

16
Array Names as Pointers

 Arrays and pointers closely related


 When array created, compiler creates internal
pointer constant for it
 Stores array’s starting address
 Name of array becomes name of pointer constant.
 Therefore, array without a bracket and a subscript
represents the starting address of the array
 An array name is a pointer constant
 Stored address cannot be changed by an
assignment statement

17
Array Names as Pointers (ctd’)

int num[6]={2,1,5,8,3,7};

num num+1 num+2 num+3 num+4 num+5

2 1 5 8 3 7

*num *(num+1) *(num+2) *(num+3) *(num+4) *(num+5)

2 1 5 8 3 7

num[0] num[1] num[2] num[3] num[4] num[5]

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;

for (i=0; i<5; i++)


cout<<*(grade+i)<<“ “<<grade[i]<<“ “<<*(gPtr+i)
<<“ “<<gPtr[i]<<endl;

return 0;
}

20
Another Example (continued)

Figure 14.11: The Variable Pointed to by *gPtr Is grade[0]

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)

Figure 14.12: An Offset of Three from the Address in gPtr

23
Another Example (continued)

Table 14.1: Array Elements May Be Accessed in Two Ways

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;

cout << "Type in a word: " ;


cin >> word;

p=&word[0]; //make p point to the memory location


// of the first array element

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

 When we no longer need storage space allocated by


the new instruction, we can release it using the
delete instruction. Suppose we have allocated
storage space for a pointer to a single integer like
this:
int* p;
p = new int ;
 When we no longer need the storage space taken up
by the integer, we simply execute the instruction:
delete p;

29
Using delete with arrays

If we have allocated space for a whole sequence of


integers, using a new instruction like this:
int* p;
p = new int[22];
then we should deallocate (release) the storage
space using the delete instruction followed by empty
array brackets.
 For example, to deallocate an array of elements
pointed to by the pointer variable p, we would write:
delete [] p;

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;

cout<<"Before swap: num1= "<<num1<<" and num2= "<<num2<<endl;


swap(&num1, &num2);
cout<<"After swap: num1= "<<num1<<" and num2= "<<num2<<endl;
return 0;
}
33
Program output: swap() function with
pointer parameters
Before swap: num1= 30 and num2= 50
After swap: num1= 50 and num2= 30

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’)

 An array parameter in a function can always


be replaced by a pointer parameter

void fun(int list[], int size) void fun(int *list, int size)

void fun(char str[]) void fun(char *str)

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

 You can return a pointer from a function


 For example:
 Write a function CopyArray() that takes as
parameters an integer array and its size and
returns a new array which is a copy of the array
argument

int* CopyArray(int *list, int size)

39
A Wrong Way to Return a Pointer
//!!!!WRONG COPY FUNCTION!!!!!!!
#include<iostream>
using namespace std;

int* CopyArray(int *, int);

int* CopyArray(int *list, int size)


{

int result[6],i;

for (i=0;i<size; i++)


{
result[i]=list[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);

for (i=0; i<6; i++)


cout<<p[i]<<endl;
return 0;
}
The output will be incorrect. The error is in the function definition. Because
the array result is a local variable it does not exist when the function returns

41
The Correct Way to Return a Pointer
//Corrected COPY FUNCTION!!!!!!!
#include<iostream>
using namespace std;

int* CopyArray(int *, int);

int* CopyArray(int *list, int size)


{ Memory allocated with the new
int i; operator remains available until
int *result=new int [size]; you explicitly free it or the
program terminates.
for (i=0;i<size; i++)
{
result[i]=list[i];
}

return result; Main program is the same as in


}
previous slide.

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

The contents where ptr points to, i.e. the structure,


and then use the usual dot notation to access members

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

Program 14.13: Pointer Array Example


45
Arrays of Pointers (continued)

Figure 14.27: The Addresses Contained in the seasons[] Pointers

46

You might also like