Discussion
What will be the output of the program (sample.c) given below if it is executed from the command line?
cmd> sample one two three
/* sample.c */
#include <stdio.h>
int main(int argc, char *argv[])
{
int i=0;
i+=strlen(argv[1]);
while(i>0)
{
printf("%c", argv[1][--i]);
}
return 0;
}
Answer: C
Correct answer: eno
argv[1] is "one", so i becomes 3. The loop then prints argv[1][--i] for i = 2, 1 and 0 - that is 'e', 'n', 'o' - and stops when i reaches 0.
The pre-decrement is what makes the indexing correct: it steps to 2 before the first access, so the terminating null at index 3 is never read. Only the first argument is touched; "two" and "three" are ignored entirely.
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