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 condition tests argv rather than *argv, and argv is a pointer into the array - it is never itself null however far it is advanced.

The loop therefore never terminates. It prints argv[0], then the terminating null pointer, then whatever lies beyond the array, walking off the end of the block until it reaches unmapped memory and the program is killed. One * separates this from the working version: the null to test for is the one stored in the array.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.