Machine-translated by Google. Questions are authored in English.
Top

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;
}

 

  • A.three two one
  • B.owt
  • C.eno
  • D.eerht

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.