We have the following C code in a function main string stra
We have the following C++ code in a function main():
string str_a = \"ABCDE\" ;
string str_b = \"XYZUV\" ;
string str_c = \"TAMU\" ;
string * ptr1 = NULL;
string * ptr2 = &str_b ;
ptr1 = &str_a ;
ptr1 = &str_c ;
cout << *ptr1 << endl;
cout << ptr1 << endl;
cout << *ptr2 << endl;
cout << ptr2 << endl;
What would be displayed when the above code segment is executed?
(a)
NULL
{the address of str_a}
XYZUV
{the address of str_b}
(b)
{the address of str_a}
ABCDE
{the address of str_b}
(c)
ABCDE
{the address of str_a}
XYZUV
{the address of str_b}
(d)
TAMU
{the address of str_c}
XYZUV
{the address of str_b}
(e)
ABCDE
XYZUV
{the address of str_a}
{the address of str_b}
(f)
TAMU
{the address of str_c}
ABCDE
{the address of str_a}
(g) None of (a) through (f) is a correct answer.
Solution
Answer:D
(d)
TAMU
{the address of str_c}
XYZUV
{the address of str_b}
Explanation:
string * ptr1 = NULL;
string * ptr2 = &str_b ;
ptr1 = &str_a ;
ptr1 = &str_c ;
cout << *ptr1 << endl;
cout << ptr1 << endl;
cout << *ptr2 << endl;
cout << ptr2 << endl;
In first line ptr1 assigned with NULL
in line 2, ptr2 value assigned with str_b. So now ptr2 value is XYZUV
in line 3, ptr1 value is assigned with str_a. so ptr1 value is ABCDE
in line 3, ptr1 value is assigned with str_c. so ptr1 value is TAMU
So finally ptr1 value is TAMU and ptr2 value is XYZUV


