Discussion
What will be the output of the following C code (run without any command line arguments)?
#include <stdio.h>
int main(int argc, char *argv[])
{
while (*argv++ != NULL)
printf("%s\n", *argv);
return 0;
}
Answer: A
Correct answer: Segmentation fault/code crash
The post-increment is the trap. The condition tests *argv, which is argv[0] and non-null, and then advances the pointer - so by the time the body runs, *argv is argv[1].
With no arguments argv[1] is the terminating null pointer, so the very first printf is handed NULL for %s. The loop tests one element and prints the next, which is exactly one element out of step; moving the increment into the printf instead, as the companion question does, corrects it.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development