Answered step by step
Verified Expert Solution
Link Copied!

Question

00
1 Approved Answer

( 2 pts ) Part 2 : Understand References and Pointers In part 2 , you will be working in a group to review the

(2 pts) Part 2: Understand References and Pointers
In part 2, you will be working in a group to review the references in C++, and we will introduce the concept of pointers.
Files needed for this part: sentence.cpp Revisit references:
Suppose our main function is as follows:
int main(){
string sentence;
get_sentence(sentence);
cout << sentence << endl;
return 0; }
In last lab, we know that in order to change the value of the string sentence inside the get_sentence() function, we need to add an ampersand (&) in front of the parameter. This is called pass by reference, i.e., by using the following function:
1
void get_sentence(string &s);
The reference variable s in the parameter list refers to the memory location of the argument, sentence. Therefore, if we update s in get_sentence() function, sentence in main() will be changed as well. This is accomplished by using a very important concept implicitly, pointers.
Introduction to Pointers
In C/C++, pointers are powerful entities that allow you to manage memory and manipulate data directly.
A pointer is a variable that holds the memory address of another variable.
To declare a pointer, use the data type followed by an asterisk (*) and the pointer name. For example: int number =42;
int *ptr = &number; //Declare and Initialize ptr with the address of 'number' Now, our pointer variable, ptr, holds the memory address of number.
(Note, you may use &var to get the memory address of var)
To access/update the value stored at the memory address pointed to by a pointer, use the dereference operator (*). For example:
cout <<*ptr << endl; // the value of number will be printed, which is 42*ptr =50; //number is changed to 50
Since reference variables is only available in C++, you are still required to understand how to use pointers to achieve the same goal. Now, change the function prototype to:
void get_sentence(string *s);
Answer the following questions:
1. Can the value of the string (sentence) be changed with the modified function prototype? If so, how? 2. Compared to using reference variables, what other modifications are required when making the function call and inside the function?
3. What is the difference between an ampersand (&) and an asterisk (*) added in front of the parameter? Use a diagram to explain.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions