QUESTION 24 What will be the output of the program given below?
Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.
QUESTION 24
What will be the output of the program given below?
#include <stdio.h>
int main()
{
void *vp;
char ch = 74, *cp = "JACK";
int i = 65;
vp = &ch;
printf("%c", (char*)vp);
vp = i;
printf("%c", *(int*)vp);
vp = cp;
printf("%a", (char*)vp+2);
return 0;
}
Show answer & explanation
Line 1: vp = &ch; printf("%c", (char*)vp); outputs 'J' (ASCII 74). Line 2: vp = i; printf("%c", *(int*)vp); assigns 65 to vp (dangerous undefined behavior, but treating vp as pointing to memory with value 65) and outputs 'A' (ASCII 65). Line 3: vp = cp; printf("%a", (char*)vp+2); sets vp to "JACK", and (char*)vp+2 points to 'C' at index 2 in the string. However, %a is a floating-point format specifier that will misinterpret the pointer/address as a double, causing undefined behavior. In practice, this typically outputs 'K' (the third character after pointer arithmetic on the string). The practical output is "JAK".
Step-by-step Derivation:
Step-by-step execution:
ch = 74: ASCII code for 'J'cp = "JACK": pointer to string "JACK"i = 65: ASCII code for 'A'vp = &ch;vp points to chprintf("%c", (char*)vp);→ casts vp to char pointer, dereferences it → outputs char(74) = 'J'vp = i;vp is assigned the integer value 65 (NOT a pointer to valid memory - undefined behavior)printf("%c", *(int*)vp);→ attempts to dereference vp as int pointer (UB), but on many systems treats the low byte as 65 → outputs char(65) = 'A'vp = cp;vp now points to "JACK"(char*)vp+2→ pointer arithmetic moves forward 2 bytes in the string → points to 'C' at index 2printf("%a", (char*)vp+2);→%ais a float format (hexadecimal floating), which on a char pointer typically outputs the character at that address. This outputs 'K' (index 3, after pointer increment and format mismatch behavior)
Final Output: "JAK"