Working on C Practice Exercises for each of the following wr
Working on C++ Practice Exercises:
for each of the following, write a single statement that performs the specified task. assume that long variables value1 and value2 have been declared and value1 has been initialized to 200000.
a) declare the variable longPtr to be a pointer to an object of type long
b) assign the address of variable value1 to pointer variable longPtr
c) print the value of the object pointed to by longPtr
d) assign the value of the object pointed to by longPtr to variable value2
e) print the value of value2
f) print the address of value1
g) print the address stored in longPtr. Is the value printed the same as value1 address?
Solution
a) declare the variable longPtr to be a pointer to an object of type long
Ans:long *longPtr; //declaring a pointer variable of type long
b) assign the address of variable value1 to pointer variable longPtr
Ans:longPtr=&value1; //longPtr now contain the address of value1
c) print the value of the object pointed to by longPtr
Ans:cout<<*(longPtr); //*(longPtr) will give the content stored at the object pointed by the longPtr
d) assign the value of the object pointed to by longPtr to variable value2
Ans:value2=*(longPtr); //value2 will now have the content stored at the object pointed by the longPtr i.e //content stored at value1
e) print the value of value2
Ans:cout<<value2; //print value of value2
f) print the address of value1
Ans:cout<<longPtr; //print address of value1 i.e content stored at the pointer variable longPtr
g) print the address stored in longPtr. Is the value printed the same as value1 address?
Ans:cout<<longPtr; Yes it will be the same as value1 address. //it will same as value1 address as longPtr is //nothing but containing the address of value1 only.
