Answered step by step
Verified Expert Solution
Question
1 Approved Answer
( 2 pts ) Part 2 : Understand References and Pointers In part 2 , you will be working in a group to review the
pts Part : Understand References and Pointers
In part 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;
getsentencesentence;
cout sentence endl;
return ;
In last lab, we know that in order to change the value of the string sentence inside the getsentence function, we need to add an ampersand & in front of the parameter. This is called pass by reference, ie by using the following function:
void getsentencestring &s;
The reference variable s in the parameter list refers to the memory location of the argument, sentence. Therefore, if we update s in getsentence function, sentence in main will be changed as well. This is accomplished by using a very important concept implicitly, pointers.
Introduction to Pointers
In CC 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 ;
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 accessupdate 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 ptr ; number is changed to
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 getsentencestring s;
Answer the following questions:
Can the value of the string sentence be changed with the modified function prototype? If so how? Compared to using reference variables, what other modifications are required when making the function call and inside the function?
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
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started