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

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

 

  • A.Segmentation fault/code crash
  • B.Executable file name
  • C.Depends on the platform
  • D.Depends on the compiler

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.