Question: Resolving Pointers in C++ Given the image above, fill in the code belo
ID: 3844294 • Letter: Q
Question
Question: Resolving Pointers in C++
Given the image above, fill in the code below with the correct symbols.
int_ a = ________;
int_ b = __ a;
int * OR & a = [ Select ] 3 OR new int(3) ;
int [ Select ] * OR & b = * OR & a;
Explain why your answer is correct. I am not sure which choice would be correct. If * is required or & is selected, please explain why those are the correct symbols. For example, int* a would be correct if a is a pointer to an integer, and so on.
Explanation / Answer
Pointers are easy topic if understood correctly, let's uderstand the situation here. We have two variable a and b and both hold 3. Now, the correct answer to your problem would be this:
int *a= new int(3);
int &b = *a;
How ? Let us break it, the first statement int* a actually creates a pointer a to point an integer value. If you go on to write 3 directly that would be an illegal conversion because 3 is an int value and on the left side you have int * i.e. pointer. So, we created a new integer 3 and pointed that pointer the value 3.
Now, b is an reference variable here it points to the direction of *a i.e. value at pointer a. If you had written here &a that would have been a double pointer conversion to int on the left side which is again invalid. A reference has to be initialized when created and that to an integer value, as value at a is an integer we can initialize it to that.
You can also print a and b by the following command:
cout << *(&b) <<" "; //value at direction of b
cout << *a; //value at a
I hope you understood it, if you have any further doubts let me know !
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.