QUESTION 22 Which of the line(s) generates error in the program given below?
Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.
QUESTION 22
Which of the line(s) generates error in the program given below?
#include <stdio.h>
int main()
{
struct main
{
unsigned int w : 3; //Line 1
char c[]; //Line 2
};
int str[10] = {"one", "two", "three"}; //Line 3
printf("%c", p.c);
return 0;
}
Show answer & explanation
Answer: B. Line 2
Line 2 generates a compilation error because flexible array members (unsized arrays) cannot be declared in a structure in C. A struct member must have a known, fixed size at compile time. Flexible array members are only allowed as the last member of a struct and require special handling (typically via malloc for dynamically sized data). Line 3 is also problematic (mixing string literals with int array), but Line 2 is the primary structural error that prevents compilation.
Step-by-step Derivation:
In C, struct members must have well-defined sizes:
- Line 1:
unsigned int w : 3;is valid—a 3-bit bitfield. - Line 2:
char c[];is invalid—an unsized array cannot be a struct member. Arrays must either have a fixed size (e.g.,char c[10];) or be a pointer (e.g.,char *c;). Flexible array members (C99 feature) are only allowed as the last member and require special initialization. - Line 3: Also has a type mismatch (string literals assigned to int array), but the compilation fails at Line 2 first.
- Additionally, the code references undefined variable
pin the printf, which would be another error.