Discussion
What will be the output of this program (prg_2.c)?
#include <stdio.h>
int main(int argc,char* argv[])
{
printf("%s",argv[argc]);
return 0;
}The program is run as:
C:\TC\BIN>prg_2.exe Help .Com
Answer: A
Correct answer: (null)
The program prints argv[argc]. With the command line prg_2.exe Help .Com there are three entries in use - argv[0] is the program name, argv[1] is Help, argv[2] is .Com - so argc is 3 and the program is asking for argv[3]. That is one past the last argument, and the standard requires it to be a null pointer: argv[argc] is always null, which is what allows a program to iterate over its arguments until it meets the null rather than counting them. Passing a null pointer to %s is strictly undefined behaviour, but every widely used C library detects it and prints the literal text (null) rather than crashing, and that is the output the question expects. The distractors are the values one index lower or higher in the reader’s mental model: .Com is argv[argc-1], Help is argv[1], and the command line itself is never a value of argv at all - the shell splits it before the program sees it. The program listing and its command line had both been lost from this record and are restored above.
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