CSE 2050/C++ QUIZ 5 [6 questions, 19 points, 15 min] WRITE YOUR MAJOR, NAME and ID4: Q1. What will be printed from this code? [2] 1 // more pointers 2 #include <iostream> 3 using namespace std; 4 5 int main () 6 { 7 int firstvalue = 5, secondvalue = 15; 8 int * p1, * p2; 9 10 p1 = &firstvalue; // p1 = address of firstvalue 11 p2 = &secondvalue; // p2 = address of secondvalue 12 *p1 = 10; // value pointed to by p1 = 10 13 *p2 = *p1; // value pointed to by p2 = value pointed to by p1 14 p1 = p2; // p1 = p2 (value of pointer is copied) 15 *p1 = 20; // value pointed to by p1 = 20 16 17 cout << "firstvalue is " << firstvalue << '\n'; 18 cout << "secondvalue is " << secondvalue << '\n'; 19 return 0; 20 } ANS: comments above should be removed in question firstvalue is 10 secondvalue is 20 Q2. What is the mistake below? [1] int main () { int * p1, p2; *p1 = 10; *p2 = 20; cout << *p1 << *p2 << endl; } ANS. p2 is declared as an int, and not a pointer, but is used subsequently as pointer. Q3. What will be printed from this code. [3] int main () { int numbers[3]; int * p; p = numbers; *p = 10; p++; *p = 20; p++; *p = 10; p- -; *p=15; cout << numbers[0] << ", " << numbers[1] <<", " << numbers[2]; }
CSE 2050/C++ QUIZ 5 [6 questions, 19 points, 15 min] WRITE YOUR MAJOR, NAME and ID4: Q1. What will be printed from this code? [2] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // more pointers #include <iostream> using namespace std; int main () { int firstvalue = 5, secondvalue = 15; int * p1, * p2; p1 = &firstvalue; // p1 = address of firstvalue p2 = &secondvalue; // p2 = address of secondvalue *p1 = 10; // value pointed to by p1 = 10 *p2 = *p1; // value pointed to by p2 = value pointed to by p1 p1 = p2; // p1 = p2 (value of pointer is copied) *p1 = 20; // value pointed to by p1 = 20 cout << "firstvalue is " << firstvalue << '\n'; cout << "secondvalue is " << secondvalue << '\n'; return 0; } ANS: comments above should be removed in question firstvalue is 10 secondvalue is 20 Q2. What is the mistake below? [1] int main () { int * p1, p2; *p1 = 10; *p2 = 20; cout << *p1 << *p2 << endl; } ANS. p2 is declared as an int, and not a pointer, but is used subsequently as pointer. Q3. What will be printed from this code. [3] int main () { int numbers[3]; int * p; p = numbers; *p = 10; p++; *p = 20; p++; *p = 10; p- -; *p=15; cout << numbers[0] << ", " << numbers[1] <<", " << numbers[2]; }