With pointers we can actually pass x and y to a function, that function can do something with them and those variables values can actually change, so that's a quite a change in our ability to work with data.
We can reuse pointer variables
a pointer holds the memory address of a variable
A pointer can be re-assigned any number of times
Pointers can point nowhere (NULL)
The Codex of Business Writing Software for Real-World Solutions 2.pptx
Pointers by: Professor Lili Saghafi
1. 0-1
Processing Arrays
POINTERS
By : Prof. Lili Saghafi
proflilisaghafi@gmail.com
St. Francis Xavier University
Advanced Programming
Data Abstraction
@Lili_PLS
2. 0-2
Agenda
• The use of pointers
• Memory allocation
• Pointers
• Pointers and arrays
• Types of pointers
• const parameter
• Analogy
• Examples
4. 0-4
Swap function
• If we use pointers instead of using
variables or instead of using the variables
themselves or copies of the variables we
can now pass the variables around
between functions in a different way.
• If we make a change in one function
that change will actually take effect in a
different function
• This is something we couldn't do
previously ,if you've ever tried to swap the
value of two variables in a function
5. 0-5
Swap function with pointers
• if we want to swap X and Y and we pass thepass thepass thepass the
variables ( by value) to a function called swapvariables ( by value) to a function called swapvariables ( by value) to a function called swapvariables ( by value) to a function called swap
inside of the function swap the variables do
exchange values one becomes two, two
becomes one but we don't actually change
anything in the original function in thein the original function in thein the original function in thein the original function in the callercallercallercallercallercallercallercaller
because we can't, we're only working with copies
of them
• With pointers though we can actually pass x and
y to a function, that function can do something
with them and those variables values can
actually change, so that's a quite a change in
our ability to work with data.
7. 0-7
Memory
• RAM is smaller
• Data take space in RAM and any change
should happen in RAM
• Each Data type takes different space in
RAM
• Arrays are sequential space in memory
• Multidimensional Arrays are really one
dimensional array
8. 0-8
Allocation of data in memory
• Memory is a big array of bite sized cells
• it's just a huge array of cells just like any other
array
• Except every element is 1 byte wide and just like
an array every element has an address every
element of an array has an index and we can
use that index to do so-called random access on
the array
• Every location in memory has an address
9. 0-9
•your memory might look something like this, here's a very small
chunk of memory, this is 20 bytes of memory, the first 20 bytes’
•Address is there at the bottom are 0 1 2 3 and so on all the way up to
19
•When I declare variable , the system is going to set aside some
space for me in this memory to work with my variable
10. 0-10
Data Type Size
Even though we said string is a datatype but it is really
an alias for something else , “char*”
11. 0-11
Int datatype size is 4byte
Char is 1byte
The computer works with binary , 0 and 1
So the binary representation of H and 65
is here
char C equals capital H the system set aside for you one
byte in this case, it chose byte number for the byte at
address 4 and it stores the letter capital H.
12. 0-12
Pointers are just addresses
Int datatype size is 4byte
Char is 1byte
For integer variable it's
not going to just spit it
into , it treats it as one
four byte chunks so it's
actually treat it as four
one byte chunks
13. 0-13
Pointers are just addresses
• For String it will add 0 too to know when our string
ended.
• When we're talking about memory addresses we usually
do so using hexadecimal notation
• We convert all of these from decimal to hexadecimal
notation
• This is how we refer to memory so instead of being 0
through 19 we have is 0 X 0 through 0 X 1 3 those are
the 20 bytes of memory that we have
Exp: 0013FF60
15. 0-15
What is a
Pointer?
count (int type, 4 bytes)
00
status (short type, 2 bytes)
letter (char type, 1 byte)
pStatus:
pLetter:
0013FF60
.
.
0013FF61
0013FF62
0013FF63
0013FF64
0013FF65
0013FF66
.
.
pCount:
13
FF
60
pCount is 0013FF60
00
13
FF
64
pStatus is 0013FF64
00
13
FF
66
pLetter is 0013FF66
.
.
05
02
41
int count = 5;
short status = 2;
char letter = 'A';
int* pCount = &count;
short* pStatus = &status;
char* pLetter = &letter;
pCount = &count;
&: address operator
&count means the address of
count
*: dereference operator
*pCount means the value
pointed by pCount
Memory is a big array of byte-size cells
17. 0-17
What is a Pointer?
Arrays are closely related to pointers in programming
but the important difference between them is that, a
pointer variable takes different addresses as value
w h e r e a s , i n c a s e o f a r r a y i t i s f i x e d .
Pointer variables, simply called pointers, are designed
to hold memory addresses as their values.
Normally, a variable contains a specific value, e.g., an
integer, a floating-point value, and a character.
A pointer contains the memory address of a variableA pointer contains the memory address of a variable
t h a t i n t u r n c o n t a i n s a s p e c i f i c v a l u e .
20. 0-20
*: DEREFERENCE operator
*pk means the value pointed by pk
pk which points at k, which is in k has to change
to 5
pk holds the address of K , pointed by pk
21. 0-21
&K means , pk
gets the address of
k
A pointer is a data
item whose value is
an address
22. 0-22
if we walk along the length of the arrow
at the very tip of that arrow we will find
the location in memory where K lives
pointers PK gives us
the information we
need to find K in
memory
26. 0-26
Dereferencing
• Dereferencing is that we go to the reference and we
change the value there
• if we have a pointer and it's called PC and it points to a
character then we can say * PC and star PC is the name
of what we'll find if we go to the address PC what we'll
find there as a character and star PC is how we refer to
the data at that location so we could say something like
• * PC = D or something like that and that means that
whatever was at memory address PC whatever character
was previously there is now capital D
• In order to change the variable you need to GO to that
variable not only have the address of that variable and
* operator is for that purpose
*pc means the value pointed by pc
*pc holds the address of c
*: DEREFERENCE operator
29. 0-29
The star is actually part of both the type
name and part of the variable name
30. 0-30
Caution
You can declare two variables on the same line.
For example, the following line declares two int variables:
int i = 0, j = 1;
Can you declare two pointer variables on the same line as
follows?
int* pI, pJ;
No, this line is equivalent to , one is pointer and the other
one is not
int *pI, pJ;
31. 0-31
Analogy
My TA function
• Lets think about the function TA
• Grade book to update by TA function
• Correction and input into the grade book for updating
• Passing back the GB
• Now it is up to me , calling function or caller , to
integrate the GB of TA function ( calling Function)
• Isn’t it better that TA function could actually work with GB
not the copy of that ?
• This is the way that pointers work , they actually pass the
real data among the functions not the copy of them
• Any changes in CALLING function affect CALLER/CALLY
function as well .
32. 0-32
Declaration of Pointers
• A pointer is a variable whose value is
the address of another variable.
• Like any variable or constant, you must
declare a pointer before you can work
with it.
• The general form of a pointer variable
declaration is:
3
2
type *var-name;
33. 0-33
3
3
Declare a Pointer
Like any other variables, pointers must be declared before they
can be used.
To declare a pointer, use the following syntax:
dataType* pVarName;
Each variable being declared as a pointer must be preceded by an
asterisk (*). For example, the following statement declares a
pointer variable named pCount that can point to an int variable
called Count.
int* pCount;
Address of
pCount
Address of variable count Address of variable count 5
pCount count
RunTestPointer*: dereference operator
*pVarName means the value pointed by
pVarName
34. 0-34
#include <iostream>
using namespace std;
int main()
{ int count = 5;
int* pCount = &count; //&count means the address
of count
cout << "The value of count is " << count << endl;
cout << "The address of count is " << &count << endl;
cout << "The address of count is " << pCount << endl;
cout << "The value of count is " << *pCount << endl;
return 0;}
The value of count is 5
The address of count is 00D4F8B0
The address of count is 00D4F8B0
The value of count is 5
Address of
pCount
Address of variable count Address of variable count 5
pCount count
*: dereference operator
*pVarName means the value pointed by
pVarName
35. 0-35
Initializing Pointer
Like a local variable, a local pointer is assigned an
arbitrary value if you don’t initialize it.
A pointer may be initialized toinitialized to 00, which is a special
value for a pointer toto indicate that the pointer pointsindicate that the pointer points
to nothing.to nothing.
You should always initialize pointers to prevent
errors.
Dereferencing a pointer that is not initialized could
cause fatal runtime error or it could accidentally
modify important data.
37. 0-37
nullptr
A pointer may be initialized to 0, which is a special
value to indicate that the pointer points to nothing.
To prevent errors, you should always initialize
pointers. Or setting it to NULL
A number of C++ libraries including <iostream>
define NULL as a constant with value 0.
It is more descriptive to use NULL than 0.
C++11 introduced a new keyword nullptrnullptr for null
pointer.
Using nullptr is better than using NULL, because
NULL may be accidentally redefined in the
program.
C++11: The keyword nulptr is
defined in C++11
*par = time( NULL );
The value pointed by par
&count means the address of count
*: dereference operator
*pCount means the value pointed by pCount
38. 0-38
nullptr
• C++11 adds a null pointer constant
called nullptr.
• The use of nullptr should be preferred
over 0 or NULL.
•• Some compilers added a warning for theSome compilers added a warning for the
use ofuse of 00 as a pointeras a pointer
• they are strongly encouraging you to
use nullptrnullptr.
42. 0-42
How it works
5 00D4F8B0
count
int count;
count = 5
int* pCount = &count
pCount
• & operator, & some variable name, is the address
of variable count, so pCount gets the address of
variable name count.
• *pCount means the value pointed by pCount , here
is 5
43. 0-43
Pointer and Arrays
• An array name is just a pointer to its
first element
• The function which can accept a pointer,
can also accept an array as shown in the
following example:
44. 0-44
Keep in mind
• When we made a change to the array when we
passed an array as a parameter to a function or
as an argument to a function the contents of the
array actually changed, in both the cally and in
the caller which for every other kind of variable
was not the case
ArrayPointer Run
An array name is just a pointer to its
first element
45. 0-45
Arrays are just pointers
• The name of array is a pointer to the first element of
that array.
• When we pass value by pointers to a function( as
an argument of the function) after what ever
functions do to them the values of variable changes , in
the same manner with arrays
• When we pass an array as an argument to a
function the content of array is actually change in
both cally and caller ,
• For any other kind of variable it was not the case .
46. 0-46
Data Type Size
Even though we said string is a datatype but it is really
an alias for char*
48. 0-48
Data Type Size
Every address in memory is 32bit or 64bit, long
The size depends on the type of IDE
49. 0-49
• In a 64-bit system every address memory
is 64 bits long
• if you're using any 32-bit machine (a 32-bit
machine it just means that every address
in memory is 32 bits long ) and so the 32
bits is 4 bytes
• so what char* is 4 or 8 bytes depending on
your system
51. 0-51
Revisiting
How pointer works
*: DEREFERENCE operator
*pk means the value pointed by pk
pk which points at k
*pk means the value pointed by
pk which is in k has to change to
35
54. 0-54
How pointer works
*: dereference operator
*pk means the value pointed by pk
&m means the address of m
&m means pk gets the address of variable name m ,
so pk no longer points to k , but to m
55. 0-55
How pointer works
& operator
& some variable name, is the address of variable that
variable name here is m
so pk gets the address of variable name m ,
so pk no longer points to k , but to m
56. 0-56
Pointer is variable that it’s value is an address
pk gets the address of k, the address of
memory that holds k box( variable)
pk gets the
address of K
The value that PK
refer to is int
58. 0-58
Type of pointer
• Type of pointer defines what type of data
you can find at that memory address
59. 0-59
The importance of POINTERS
• Some C++ tasks are performed more
easily with pointers, and other C++ tasks,
such as dynamic memory allocation,
cannot be performed without them.
(vectors)
• As you know every variable is a memory
location and every memory location has its
address defined which can be accessed
using ampersand (&) operator which
denotes an address in memory.
60. 0-60
&: address operator vs *: dereference operator
&: address operator
&count means the address of count
*: dereference operator
*pCount means the value pointed by pCount
0-60
61. 0-61
Dereferencing
Referencing a value through a pointer is
called indirection.
The syntax for referencing a value from a
pointer is *pointer
Dereferencing gets you a reference to the
actual object the pointer is pointing to.
We go to reference and we change the value
there.
* is dereference operator.
62. 0-62
example
For example, you can increase count using
count++; // direct reference, increment the
value in count by 1
or
(*pCount)++; // indirect reference, the
value in the memory pointed by pCount
is incremented by 1
• Using my TA function to change the
assignments
0-62
63. 0-63
Dereferencing a pointer
• A pointer is a variable that tells the
computer *where* a variable is
stored.
• Dereferencing a pointer tells the
computer *what* is in the spot
where a pointer is pointing to.
64. 0-64
Example
DEREFERENCING is using a pointer with *.
(USING A VALUE)
exp: (*pCount)++; // indirect reference, the
value in the memory pointed by pCount is
incremented by 1
REFERENCING is using it without *. (USING
ADDRESS)
exp:count++; // direct reference
0-64
65. 0-65
Pointer Type
A pointer variable is declared with a type such as int,
double, etc.
You have to assign the address of the variable of the
same type.
It is a syntax error if the type of the
variable does not match the type of
the pointer
For example, the following code is wrong.
int area = 1;
double* pArea = &area; // Wrong
66. 0-66
Passing by value
• We are passing data between functions
• All data passes between functions are
passed by value
• We are not actually passing that value to
the function
• We are passing a copy of that data to
functions
If we are using pointers , passing values to or
between function by pointers , inside of the
function , the values of those variable will
change
67. 0-67
Passing pointers to functions in C++
• C++ allows you to pass a pointer to a
function.
• To do so, simply declare the function
parameter as a pointer type.
Following a simple example where we pass an
unsigned long pointer to a function and change the
value inside the function which reflects back in the
calling function ( cally and caller will change):
Exp: My notebook
68. 0-68
#include <iostream>
#include <ctime>
using namespace std;
void getSeconds(unsigned long *par); // function prototype
int main ()
{ unsigned long sec;
getSeconds( &sec ); // print the actual value
cout << "Number of seconds :" << sec << endl;
return 0;
}
// Function body
void getSeconds(unsigned long *par) {
// get the current number of seconds
*par = time( NULL );
return; }
Number of seconds :1479164202
we pass an unsigned long
pointer to a function
change the value inside the
function which reflects back
in the calling function ( cally
and caller will change):
69. 0-69
Effect of Assignment = operator in
case of pointers
• Suppose pX and pY are two pointer
variables for variables x and y, as shown in
next figure
• To understand the relationships between the
variables and their pointers, let us examine
the effect of assigning
pY to pX
*pY to *pX.
*: dereference operator
*pX means the value
pointed by pX
pX point at X
pY point at Y
70. 0-70
Effect of Assignment =
Address of x Address of x 5
pX x
Address of y Address of y 6
pY y
Address of y Address of x
pX
Address of y Address of y
pY
Address of x Address of x
pX
Address of y Address of y
pY
pX = pY; *pX = *pY;
5
x
6
y
6
x
6
y
*: dereference operator
*pX means the value
pointed by pX
pX point at X
pY point at Y
pX point at X
pY point at Y
*pX means
the value
pointed by pX
71. 0-71
Using const with Pointers
• You learned how to declare a constant using the
const keyword.
• A constant cannot be changed once it is
declared.
• You can declare a constant pointer.
• For example, see the following code:
double radius = 5;
double* const pValue = &radius;
const double * const pValue = &radius;
Constant data Constant pointer
so pValue gets the address of
variable name radius
72. 0-72
Arrays and Pointers
An array variable without a bracket and a subscript actually
represents the starting address of the array.
In this sense, an array variable is essentially a pointer.
Suppose you declare an array of int value as follows:
int list[6] = {11, 12, 13, 14, 15, 16};
11 12 13 14 15 16
list+0 list+1 list+2 list+3 list+4 list+5
73. 0-73
Array Pointer
• *(list + 1) is different from *list + 1.
• The dereference operator (*) has
precedence over +.
• So, *list + 1 adds 1 to the value of the first
element in the array,
• while *(list + 1) dereference the element
at address (list + 1) in the array.
RunPointerWithIndex
RunArrayPointer
74. 0-74
Passing Pointer Arguments
• A pointer argument can be passed by value or
by reference.
• For example, you can define a function as follows:
void f(int* p1, int* &p2) // we can actually pass p1
and p2 To the function , function do something to
them and the values of the variables change ( in
p1 and p2)
• which is equivalently to
typedef int* intPointer;
void f(intPointer p1, intPointer& p2)
• Here p1 is pass-by-value and p2 is pass-by-
reference.
RunTestPointerArgument
75. 0-75
array parameter or pointer
parameter
void m(int list[], int size) can be replaced by void m(int* list, int size)
void m(char c_string[]) can be replaced by void m(char* c_string)
76. 0-76
#include <iostream>
using namespace std;
// function declaration
double getAverage(int *arr, int size);
int main ()
{ // the value pointed by arr is an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;}
double getAverage(int *arr, int size) // function body
{ int i, sum = 0; double avg; for (i = 0; i < size; ++i)
{ sum += arr[i]; }
avg = double(sum) / size;
return avg;}
Average value is: 214.4
*arr means the value pointed by
arr
The values inside arr
An array name is just a pointer to its first
element
77. 0-77
const parameter
• If an object value does not change, you
should declare it const to prevent it from
being modified accidentally.
RunConstParameter
78. 0-78
#include <iostream>
using namespace std;
void printArray(const int*, const int);
int main()
{
int list[6] = {11, 12, 13, 14, 15, 16};
printArray(list, 6);
return 0;
}
void printArray(const int* list, const int size)
{ for (int i = 0; i < size; i++)
cout << list[i] << " ";
}
11 12 13 14 15 16
79. 0-79
Returning a Pointer from Functions
• You can use pointers as parameters
in a function.
• Can you return a pointer from a
function? The answer is yes.
RunReverseArrayUsingPointer
80. 0-80
#include <iostream>
using namespace std;
int* reverse(int* list, int size)
{ for (int i = 0, j = size - 1; i < j; i++, j--)
{
// Swap list[i] with list[j]
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}
return list;}
void printArray(const int* list, int size)
{ for (int i = 0; i < size; i++)
cout << list[i] << " ";
}
int main()
{
int list[] = {1, 2, 3, 4, 5, 6}; int* p = reverse(list, 6); printArray(p, 6); return 0;}
6 5 4 3 2 1
81. 0-81
Array is Treated as Pointer
In C/C++, an array's name is a pointer
pointing to the first element (index 0) of the
array.
For example, suppose that numbers is
an int array, numbers is also an int pointer,
pointing at the first element of the array.
numbers is the same as &numbers[0].
*numbers is number[0];
*(numbers+i) is numbers[i].
83. 0-83
What is the difference between pointer and
reference variable
• A reference is an alias for
another variable
• whereas a pointer holds the memory
address of a variable.
• References are generally used as function
parameters so that the passed object ispassed object is
not the copy but the objectnot the copy but the object ..
84. 0-84
Reference variable
• A reference variable is an alias, that is, another
name for an already existing variable.
• Once a reference is initialized with a variable,
either the variable name or the reference name
may be used to refer to the variable.
• An object reference on the stack is only an
address that refers to the place in heap memory
where that object is kept.
85. 0-85
What is the difference between pointer and
reference variable
• A pointer can be re-assigned any number of
times while a reference cannot be re-seated
after binding.
• Pointers can point nowhere (NULL), whereas
reference always refer to an object.
• You can't take the address of a reference like
you can with pointers.
•• There's no "referenceThere's no "reference arithmeticsarithmetics"" (but you
can take the address of an object pointed by a
reference and do pointer arithmetics on it as
in &obj + 5).
86. 0-86
Processing Arrays
POINTERS
By : Prof. Lili Saghafi
proflilisaghafi@gmail.com
St. Francis Xavier University
Advanced Programming
Data Abstraction
THANK YOU
ANY QUESTION ?
@Lili_PLS