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;
}
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.
Please log in or register to report this question.