In: Computer Science
What is the output of the following C++ code?
int* length; int* width; length = new int; *length = 5; width = length; length = new int; *length = 2 * (*width); cout << *length << " " << *width << " " << (*length) * (*width) << endl;
Below is the line by line explaination of the above code -
int* length;
int* width;
Two pointer variables with name length and width are declared here
length = new int;
Pointer variable named length is assigned a memory in the program and it is now pointing(referencing) to a memory block which can hold integral value
*length = 5;
Value of 5 is stored at the memory location pointed by length
width = length;
Pointer variable named width is now pointing to the memory location pointed by length
length = new int;
Pointer variable named length is now assigned a new memory location in the program Note that the previous memory block which contains value of 5 is still pointed by width
*length = 2 * (*width);
Value to be stored at memory location pointed by length is will be two times the value at memory location pointed by width that is two times of 5 that is 10
cout << *length << " " << *width << "
"
<< (*length) * (*width)
<< endl;
On printing above values output is -
10 5 50
As value at memory location pointed by length is 10, value at memory location pointed by width is 5 and product of these 2 values is 50
I have tried to explain it in very simple language and I hope that i have answered your question satisfactorily.Leave doubts in comment section if any.