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

Discussion

What will be the output of this program (prg_3.c)?

#include <stdio.h>
#include <stdlib.h>
int main(int argc,char* argv[])
{
    int answer;

    answer=atoi(argv[1])+atoi(argv[2]);
    printf("%d",answer);
    return 0;
}

The program is run as:

C:\TC\BIN>prg_3.exe 10 20

  • A.50
  • B.60
  • C.30

Answer: C

Correct answer: 30

Command line arguments always arrive as strings, never as numbers. With the command line prg_3.exe 10 20, argv[1] is the two-character string "10" and argv[2] is "20". Adding those directly would add two pointers, which C does not even permit, so the program converts each with atoi - ASCII to integer, declared in <stdlib.h> - giving \[ 10 + 20 = 30. \] Two habits are worth taking from this. First, atoi reports no errors: given text that is not a number it simply returns 0, which is indistinguishable from a genuine "0", so production code uses strtol instead. Second, the program never checks argc before reading argv[1] and argv[2]; run with fewer arguments it would dereference a null pointer and crash. The command line had been lost from this record and is restored above.

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

Post your comment

Please log in or register to post a comment.