0 / 8 correct

Exercise 1: Pointer Basics

Trace, debug, and write pointer code

⏲ Estimated time: 25 – 30 minutes

PART A Pointer Tracing

Read each code snippet carefully. Fill in the final values of the variables after all lines have executed, then click Check.

1

Simple Dereference

int a = 5;
int* p = &a;
*p = 20;
int b = *p + 5;

After all lines execute, what are the values?

2

Two Pointers

int x = 10, y = 20;
int* p = &x;
int* q = &y;
*p = *q;
p = q;
*p = 50;

After all lines execute:

3

Pointer Arithmetic

int arr[4] = {10, 20, 30, 40};
int* p = arr;
p++;
int val = *p + *(p+2);

After all lines execute:

4

Pointer Reassignment

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:

PART B Fix the Code

Each snippet has a bug. Type the corrected line(s) in the input box and click Check.

1

Uninitialized Pointer

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:

2

Wrong Operator

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?

3

Memory Leak

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:

PART C Write a Swap Function

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: