What would print from the following segment of code Explain
What would print from the following segment of code. Explain each output and why it is what it is.
int x = 24;
int *intptr;
intptr = &x;
cout << x << endl;
cout << *intptr << endl;
cout << intptr << endl;
*intptr = 100;
cout << *intptr << endl;
cout << intptr << endl;
Solution
The output of the of the code is:
cout << x << endl; --> This prints the value in variable x, which is 24.
cout << *intptr << endl; --> This prints the value in the variable intptr is pointing to, which is also 24 right now.
cout << intptr << endl; --> This actually prints the address of the memory location of variable x. This will be hexadecimal number and will change for every execution. Let us calle this address1.
cout << *intptr << endl; --> This prints the value in the variable intptr is pointing to, which is also 100 right now. Because we changed it in the previous statement.
cout << intptr << endl; --> This still prints the same address as in the previous print statement which is address1. We changed the value in the memory location ntptr is pointing to, but the memory location is still the same, so its addreess will also also be the same.
