Understanding Pointers and Functions in C++ Lecture

CMSC202
 Computer Science II for Majors
Lecture 04 –
Pointers
Dr. Katherine Gibson
Based on slides by Chris Marron at UMBC
Last Class We Covered
 
C++ Functions
Parts of a function:
Prototype
Definition
Call
Arrays
Declaration
Initialization
Passing arrays to function
 
 
2
Any Questions from Last Time?
 
Note Taker Still Needed
A peer note taker is still needed for this class. A peer note taker
is a volunteer student who provides a copy of his or her notes for
each class session to another member of the class who has been
deemed eligible for this service based on a disability. Peer note
takers will be paid a $200 stipend for their service. Peer note
taking is not a part time job but rather a volunteer service for
which enrolled students can earn a stipend for sharing the notes
they are already taking for themselves.
If you are interested in serving in this important role, please fill
out a note taker application on the Student Support Services
website or in person in the SSS office in Math/Psychology 213.
4
Today’s Objectives
 
To review functions and how they work
 
To 
begin
 to understand pointers
Pointers are a complicated and complex concept
You may not immediately “get it” – that’s fine!
 
To learn how pointers can be used in functions
Passing in entire arrays
“Returning” more than one value
 
 
5
Functions and Arguments
 
Review of Functions
 
Here is a simple function that adds one to an
integer and returns the new value
 
Definition:
int 
AddOne
 (
int  
num
) {
   return num++;
}
Call:
int 
enrolled
 = 99;
enrolled = AddOne(enrolled);
7
Function Arguments
 
What is happening “behind the scenes”?
 
When the 
AddOne()
 function is called, the
value
 of the variable is passed in as an argument
The value is saved in 
AddOne
’s local variable 
num
 
Changes made to 
x
 do not affect anything
outside of the function 
AddOne()
This is called the 
scope
 of the variable
8
Scope
 
Scope is the “visibility” of variables
Which parts of your program can “see” a variable
 
Every function has its own scope:
The 
main()
 function has a set of variables
So does the 
AddOne()
 function
 
They 
can’t
 “see” each other’s variables
Which is why we must pass arguments
and return values between functions
9
Addresses
 
Every variable in a program is stored
somewhere in the computer’s 
memory
This location is called the address
All variables have a unique address
 
Addresses are normally expressed in hex:
0xFF00
0x70BF
0x659B
10
Array Addresses
 
An array also has an address
The location of the first element of the array
 
char 
terry
[6] = 
"hello"
;
 
 
 
 
We’ll discuss arrays more later today
11
Function Scope
 
What happens when 
AddOne()
 is called?
int 
age
 = 20;
age = AddOne(age);
 
The 
value
 of 
age
 is passed in, and stored in
another variable called 
num
What is the 
scope
 of each of these variables?
 
age
 is in the scope of 
main()
 
num
 is in the scope of 
AddOne()
12
 
The blue box represents scope
The “house” shape is a variable’s
name, address, and value
main()
Function Calls
13
 
When 
main()
 calls 
AddOne()
The value is passed in, and stored in 
num
AddOne()
main()
Function Calls
14
20
 
When the 
AddOne()
 function changes 
num
,
what happens to the 
age
 variable?
Nothing!
 
AddOne()
main()
Function Calls
15
21
 
How do we update the value of 
age
?
By 
returning
 the new value and assigning it to 
age
AddOne()
main()
Function Calls
16
21
 
What happens when the function returns?
The function is over
AddOne()
 and 
num 
are “out of scope”
AddOne()
main()
Function Calls
17
And are
no longer
available
to us!
Pointer Introduction
 
Pointers
 
A pointer is a variable whose value is an
address to somewhere in memory
 
cout << 
"x   is " 
<< x << endl;
cout << 
"ptr is " 
<< ptr << endl;
 
This will print out something like:
x   is 37
ptr is 0x7ffedcaba5c4
19
Pointers
 
Pointers are incredibly useful to programmers!
 
Allow functions to
Modify multiple arguments
Use and modify arrays as arguments
Programs can be made more efficient
Dynamic objects can be used
We’ll discuss this later in the semester
20
Creating Pointers
 
A pointer is just like any regular variable
It must have a type
It must have a name
It must contain a value
 
To tell the compiler we’re creating a pointer,
we need to use 
*
 in the declaration
int 
*
myPtr
;
 
21
Pointer Declarations
 
All of the following are valid declarations:
int 
*
myPtr
;
int
* 
myPtr
;
int 
* 
myPtr
;
Even this is valid (but don’t do this):
int
*
myPtr
;
 
The spacing and location of the star (“
*
”)
don’t matter to the compiler
22
this is the most
common way
Pointer Declarations
 
Since position doesn’t matter, why use this?
int 
*
myPtr
;
 
What does this code do?
int 
*
myPtr
,  
yourPtr
,  
ourPtr
;
It creates one pointer and two 
integers
!
 
What does this code do?
int 
*
myPtr
, *
yourPtr
, *
ourPtr
;
It creates three integers!
23
 
 
Pointers and “Regular” Variables
 
As we said earlier, pointers are just variables
Instead of storing an int or a float or a char,
they store an address in memory
24
 
“regular” variable
 
value
 
address
 
value
 
address
 
pointer variable
 
(where it
points in
memory)
 
(where it
lives in
memory)
Assigning Value to a Pointer
 
The value of a pointer is always an ???
 
To get the address of any variable, we use
an ampersand (“
&
”)
 
int
  
x
 = 5;
int 
*
xPtr
;
// xPtr "points to" x
xPtr = &x;
25
address
Assigning to a Pointer
 
All of these are valid assignments:
int
  
x
 = 5;
int 
*
ptr1
 = &x;
int 
*
ptr2
;
ptr2 = &x;
int 
*
ptr3
 = ptr1;
26
Assigning to a Pointer
 
This is not a valid assignment – why?
int
  
x
 = 5;
char 
*
ptr4
 = &x;
 
Pointer type 
must
 match the type of the variable
whose address it stores
Compiler will give you an error:
cannot convert ‘int*’ to ‘char*’ in initialization
27
 
When we assign a value to a pointer, we are
telling it where in memory to point to
 
// create both variables
double
 
val
;
double
 *
ptr
;
// assign values
val = 5.6;
ptr = &val;
 
Making Pointers “Point”
28
5.6
0xBB08
The Asterisk and the Ampersand
 
Review: The Ampersand
 
The ampersand
Returns the address of a variable
Must be placed in front of the variable name
 
int
  
x
 = 5;
int 
*
varPtr 
= &x;
int
  
y
 = 7;
varPtr = &y;
 
 
30
The Asterisk (or “Star”)
 
The star symbol (“
*
”) has two purposes when
working with pointers
 
The first purpose is to tell the compiler
that the variable will store an address
In other words, “declaring a pointer”
 
int 
*
varPtr 
= &x;
void 
fxnName 
(
float 
*
fltPtr
);
 
 
31
The Asterisk (or “Star”)
 
The second purpose is to 
dereference
 a pointer
 
Dereferencing a pointer means the compiler
Looks at the address stored in the pointer
Goes to that address in memory
Looks at the value stored at that address
 
32
Dereferencing
What we do at that point depends on why the
pointer is being dereferenced
A dereference can be in three “places”
On the 
left hand side
 of the assignment operator
On the 
right hand side
 of the assignment operator
In an expression 
without
 an assignment operator
For example, a print statement
33
Dereferencing Examples
 
int 
val 
= *ptr;
 
 
 
Look at the value, but don’t change it
 
 
 
34
on the right hand side of
the assignment operator
Dereferencing Examples
 
*ptr = 36;
 
 
 
Access the variable and change its value
 
 
 
35
on the left hand side of
the assignment operator
36
Dereferencing Examples
 
cout << 
"Value stored is " 
<< *ptr;
 
 
 
Look at the value, but don’t change it
 
 
 
36
in an expression without
an assignment operator
AddTwo()
 
The 
AddTwo()
 Function
 
Let’s create a new function that
adds 2 to two integers
So 22 and 98 will become 24 and 100
 
Can we do this with a “regular” function?
(That is, without using pointers?)
No!  Functions can only 
return
 one value!
 
We must use pointers to change more than
one value in a single function
38
The 
AddTwo()
 Function
 
We want our function to look something like
this pseudocode:
 
// take in two ints, return nothing
void
 
AddTwo
( 
<two integers>
 ) {
   
// add two to the first int
   // add two to the second int
   // keep the values -- but how?
}
39
Passing Pointers to a Function
 
To tell the compiler we are passing an address
to a function, we will use 
int 
*
varPtr
 
void
 
AddTwo 
(
int 
*
ptr1
, 
int 
*
ptr2
)
 
Just like 
int 
num 
tells the compiler
that we are passing in an integer value
 
int 
AddOne 
(
int 
num
)
 
 
 
 
40
Writing 
AddTwo()
 
Given that 
AddOne()
 looks like this:
int 
AddOne 
(
int 
num
) {
  return num++;
}
 
How do we write the AddTwo function?
void 
AddTwo 
(
int 
*
ptr1
, 
int 
*
ptr2
) {
}
 
 
41
AddTwo()
 
void 
AddTwo 
(
int 
*
ptr1
, 
int 
*
ptr2
) {
   
/* add two to the value of the
      integer ptr1 points to */
   *ptr1 = *ptr1 + 2;
   
/* add two to the value of the
      integer ptr2 points to */
   *ptr2 = *ptr2 + 2;
   /* return nothing */
}
 
 
42
Calling 
AddTwo()
 
Now that the function is defined, let’s call it
 
It takes in the address of two integers
Pass it two int pointers:
 
AddTwo(numPtr1, numPtr2);
Pass it the addresses of two ints:
 
AddTwo(&num1,   &num2);
Pass it a combination:
 
AddTwo(numPtr1, &num2);
43
Literals and Pointers
 
What about the following – does it work?
 
AddTwo(&15, &3);
 
No!  
15
 and 
3
 are literals, not variables
They are not stored in memory
They have no address
(They’re homeless!)
44
Announcements
The course policy agreement is due today
Project 1 has been released
Found on Professor’s Marron website
Due by 9:00 PM on February 23rd
Get started on it now!
Next time: References
And a review of pointers
45
Slide Note
Embed
Share

Exploring the concept of pointers and functions in C++, this lecture covers the basics of functions, passing arrays to functions, and understanding how pointers can be used in functions to manipulate data. Attendees will learn about passing entire arrays and returning multiple values using pointers.


Uploaded on Apr 17, 2024 | 10 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. CMSC202 Computer Science II for Majors Lecture 04 Pointers Dr. Katherine Gibson www.umbc.edu Based on slides by Chris Marron at UMBC

  2. Last Class We Covered C++ Functions Parts of a function: Prototype Definition Call Arrays Declaration Initialization Passing arrays to function 2 www.umbc.edu

  3. Any Questions from Last Time? www.umbc.edu

  4. Note Taker Still Needed A peer note taker is still needed for this class. A peer note taker is a volunteer student who provides a copy of his or her notes for each class session to another member of the class who has been deemed eligible for this service based on a disability. Peer note takers will be paid a $200 stipend for their service. Peer note taking is not a part time job but rather a volunteer service for which enrolled students can earn a stipend for sharing the notes they are already taking for themselves. If you are interested in serving in this important role, please fill out a note taker application on the Student Support Services website or in person in the SSS office in Math/Psychology 213. 4 www.umbc.edu

  5. Todays Objectives To review functions and how they work To begin to understand pointers Pointers are a complicated and complex concept You may not immediately get it that s fine! To learn how pointers can be used in functions Passing in entire arrays Returning more than one value 5 www.umbc.edu

  6. Functions and Arguments www.umbc.edu

  7. Review of Functions Here is a simple function that adds one to an integer and returns the new value Definition: int AddOne (int num) { return num++; } Call: int enrolled = 99; enrolled = AddOne(enrolled); 7 www.umbc.edu

  8. Function Arguments What is happening behind the scenes ? When the AddOne() function is called, the value of the variable is passed in as an argument The value is saved in AddOne s local variable num Changes made to x do not affect anything outside of the function AddOne() This is called the scope of the variable 8 www.umbc.edu

  9. Scope Scope is the visibility of variables Which parts of your program can see a variable Every function has its own scope: The main() function has a set of variables So does the AddOne() function They can t see each other s variables Which is why we must pass arguments and return values between functions 9 www.umbc.edu

  10. Addresses Every variable in a program is stored somewhere in the computer s memory This location is called the address All variables have a unique address Addresses are normally expressed in hex: 0xFF00 0x70BF 0x659B 10 www.umbc.edu

  11. Array Addresses An array also has an address The location of the first element of the array char terry[6] = "hello"; We ll discuss arrays more later today 11 www.umbc.edu

  12. Function Scope What happens when AddOne() is called? int age = 20; age = AddOne(age); The value of age is passed in, and stored in another variable called num What is the scope of each of these variables? age is in the scope of main() num is in the scope of AddOne() 12 www.umbc.edu

  13. Function Calls The blue box represents scope The house shape is a variable s name, address, and value main() age 0x1000 20 13 www.umbc.edu

  14. Function Calls When main() calls AddOne() The value is passed in, and stored in num main() AddOne() age num 0x1000 0x5286 20 20 14 www.umbc.edu

  15. Function Calls When the AddOne() function changes num, what happens to the age variable? Nothing! main() AddOne() age num 0x1000 0x5286 20 20 21 15 www.umbc.edu

  16. Function Calls How do we update the value of age? By returning the new value and assigning it to age main() AddOne() age num 0x1000 0x5286 20 21 21 16 www.umbc.edu

  17. Function Calls What happens when the function returns? The function is over AddOne() and num are out of scope main() AddOne() And are no longer age num 0x5286 available to us! 0x1000 21 21 17 www.umbc.edu

  18. Pointer Introduction www.umbc.edu

  19. Pointers A pointer is a variable whose value is an address to somewhere in memory cout << "x is " << x << endl; cout << "ptr is " << ptr << endl; This will print out something like: x is 37 ptr is 0x7ffedcaba5c4 19 www.umbc.edu

  20. Pointers Pointers are incredibly useful to programmers! Allow functions to Modify multiple arguments Use and modify arrays as arguments Programs can be made more efficient Dynamic objects can be used We ll discuss this later in the semester 20 www.umbc.edu

  21. Creating Pointers A pointer is just like any regular variable It must have a type It must have a name It must contain a value To tell the compiler we re creating a pointer, we need to use * in the declaration int *myPtr; 21 www.umbc.edu

  22. Pointer Declarations All of the following are valid declarations: int *myPtr; int* myPtr; int * myPtr; Even this is valid (but don t do this): int*myPtr; this is the most common way The spacing and location of the star ( * ) don t matter to the compiler 22 www.umbc.edu

  23. Pointer Declarations Since position doesn t matter, why use this? int *myPtr; What does this code do? int *myPtr, yourPtr, ourPtr; It creates one pointer and two integers! What does this code do? int *myPtr, *yourPtr, *ourPtr; It creates three integers! 23 www.umbc.edu

  24. Pointers and Regular Variables As we said earlier, pointers are just variables Instead of storing an int or a float or a char, they store an address in memory num ptr (where it lives in memory) 0x5286 0x560B address address 20 0xFF8A value value (where it points in memory) regular variable pointer variable 24 www.umbc.edu

  25. Assigning Value to a Pointer The value of a pointer is always an ??? address To get the address of any variable, we use an ampersand ( & ) int x = 5; int *xPtr; // xPtr "points to" x xPtr = &x; 25 www.umbc.edu

  26. Assigning to a Pointer All of these are valid assignments: int x = 5; int *ptr1 = &x; int *ptr2; ptr2 = &x; int *ptr3 = ptr1; 26 www.umbc.edu

  27. Assigning to a Pointer This is not a valid assignment why? int x = 5; char *ptr4 = &x; Pointer type must match the type of the variable whose address it stores Compiler will give you an error: cannot convert int* to char* in initialization 27 www.umbc.edu

  28. Making Pointers Point When we assign a value to a pointer, we are telling it where in memory to point to val // create both variables double val; double *ptr; // assign values val = 5.6; ptr = &val; 0xBB08 garbage 5.6 ptr 0x564F garbage 0xBB08 28 www.umbc.edu

  29. The Asterisk and the Ampersand www.umbc.edu

  30. Review: The Ampersand The ampersand Returns the address of a variable Must be placed in front of the variable name int x = 5; int *varPtr = &x; int y = 7; varPtr = &y; 30 www.umbc.edu

  31. The Asterisk (or Star) The star symbol ( * ) has two purposes when working with pointers The first purpose is to tell the compiler that the variable will store an address In other words, declaring a pointer int *varPtr = &x; void fxnName (float *fltPtr); 31 www.umbc.edu

  32. The Asterisk (or Star) The second purpose is to dereference a pointer Dereferencing a pointer means the compiler Looks at the address stored in the pointer Goes to that address in memory Looks at the value stored at that address ptr val address address 0x564F 0xBB08 0xBB08 5.6 value value 32 www.umbc.edu

  33. Dereferencing What we do at that point depends on why the pointer is being dereferenced A dereference can be in three places On the left hand side of the assignment operator On the right hand side of the assignment operator In an expression without an assignment operator For example, a print statement 33 www.umbc.edu

  34. Dereferencing Examples int val = *ptr; on the right hand side of the assignment operator Look at the value, but don t change it ptr val address address 0x564F 0xBB08 0xBB08 17 value value 34 www.umbc.edu

  35. Dereferencing Examples *ptr = 36; on the left hand side of the assignment operator Access the variable and change its value ptr val address address 0x564F 0xBB08 0xBB08 17 36 value value 35 www.umbc.edu

  36. Dereferencing Examples cout << "Value stored is " << *ptr; in an expression without an assignment operator Look at the value, but don t change it ptr val address address 0x564F 0xBB08 0xBB08 36 value value 36 www.umbc.edu

  37. AddTwo() www.umbc.edu

  38. The AddTwo() Function Let s create a new function that adds 2 to two integers So 22 and 98 will become 24 and 100 Can we do this with a regular function? (That is, without using pointers?) No! Functions can only return one value! We must use pointers to change more than one value in a single function 38 www.umbc.edu

  39. The AddTwo() Function We want our function to look something like this pseudocode: // take in two ints, return nothing void AddTwo( <two integers> ) { // add two to the first int // add two to the second int // keep the values -- but how? } 39 www.umbc.edu

  40. Passing Pointers to a Function To tell the compiler we are passing an address to a function, we will use int *varPtr void AddTwo (int *ptr1, int *ptr2) Just like int num tells the compiler that we are passing in an integer value int AddOne (int num) 40 www.umbc.edu

  41. Writing AddTwo() Given that AddOne() looks like this: int AddOne (int num) { return num++; } How do we write the AddTwo function? void AddTwo (int *ptr1, int *ptr2) { } 41 www.umbc.edu

  42. AddTwo() void AddTwo (int *ptr1, int *ptr2) { /* add two to the value of the integer ptr1 points to */ *ptr1 = *ptr1 + 2; /* add two to the value of the integer ptr2 points to */ *ptr2 = *ptr2 + 2; /* return nothing */ } 42 www.umbc.edu

  43. Calling AddTwo() Now that the function is defined, let s call it It takes in the address of two integers Pass it two int pointers: AddTwo(numPtr1, numPtr2); Pass it the addresses of two ints: AddTwo(&num1, &num2); Pass it a combination: AddTwo(numPtr1, &num2); 43 www.umbc.edu

  44. Literals and Pointers What about the following does it work? AddTwo(&15, &3); No! 15 and 3 are literals, not variables They are not stored in memory They have no address (They re homeless!) 44 www.umbc.edu

  45. Announcements The course policy agreement is due today Project 1 has been released Found on Professor s Marron website Due by 9:00 PM on February 23rd Get started on it now! Next time: References And a review of pointers 45 www.umbc.edu

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#