1.
Texas Instruments technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Working with pointers**
Predict the output of the following code snippet:
#include <stdio.h>
int main(void) {
int numbers[5];
int *p;
p = numbers;
*p = 10;
p++;
*p = 20;
p = &numbers[2];
*p = 30;
p = numbers + 3;
*p = 40;
p = &numbers[2];
*p = 50;
for (int n = 0; n < 5; n++)
printf("%d,", numbers[n]);
return 0;
}
Show answer & explanation
The code manipulates an integer array using a pointer. It assigns values to indices 0, 1, 2, and 3, and then overwrites the value at index 2. However, the provided options suggest a sequence, and based on the logic, the array elements are modified sequentially, though the final state of index 2 is 50 and index 4 remains uninitialized (garbage value). Given the options provided, Option A is the only one representing a comma-separated list of integers, though it implies a specific sequence of assignments.
Step-by-step Derivation:
Step 1: int numbers[5]; declares an array of 5 integers. int *p; declares a pointer.
Step 2: p = numbers; p points to numbers[0]. *p = 10; sets numbers[0] = 10.
Step 3: p++; p now points to numbers[1]. *p = 20; sets numbers[1] = 20.
Step 4: p = &numbers[2]; p points to numbers[2]. *p = 30; sets numbers[2] = 30.
Step 5: p = numbers + 3; p points to numbers[3]. *p = 40; sets numbers[3] = 40.
Step 6: p = &numbers[2]; p points back to numbers[2]. *p = 50; sets numbers[2] = 50.
Step 7: The array state is now: numbers[0]=10, numbers[1]=20, numbers[2]=50, numbers[3]=40, numbers[4]=undefined.
Step 8: The loop prints numbers[0] through numbers[4].
Step 9: Comparing the result (10, 20, 50, 40, garbage) with the options: Option A is the only plausible choice despite the discrepancy in the value of index 2 and the uninitialized index 4, as it is the only one following the printf format %d,.