Trace, debug, and write pointer code
Read each code snippet carefully. Fill in the final values of the variables after all lines have executed, then click Check.
int a = 5;
int* p = &a;
*p = 20;
int b = *p + 5;
After all lines execute, what are the values?
int x = 10, y = 20;
int* p = &x;
int* q = &y;
*p = *q;
p = q;
*p = 50;
After all lines execute:
int arr[4] = {10, 20, 30, 40};
int* p = arr;
p++;
int val = *p + *(p+2);
After all lines execute:
int a = 1, b = 2, c = 3;
int* p = &a;
*p = *p + 10;
p = &b;
*p = *p * 2;
p = &c;
*p = a + b;
After all lines execute:
Each snippet has a bug. Type the corrected line(s) in the input box and click Check.
int* p;
*p = 42; // crash -- undefined behavior!
cout << *p;
The pointer p does not point to valid memory. How do you fix it? Write the corrected lines:
int x = 10;
int* p = &x;
int y = &p; // wrong! this is an address, not a value
The third line uses the wrong operator. What should it be?
int* p = new int(42);
p = new int(99); // leaked the first int!
delete p;
The first allocation is never freed. Write the corrected version:
This version of swap does not work — it only swaps local copies:
// BROKEN: pass-by-value -- changes don't escape the function
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
Rewrite it using pointers so it actually swaps the caller's variables. Write the complete function: