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 (Turbo C in DOS)?
cmd> sample 1 2 3

/* sample.c */
#include <stdio.h>

int main(int argc, char *argv[])
{
    int j;
    j = argv[1] + argv[2] + argv[3];
    printf("%d", j);
    return 0;
}

 

  • A.6
  • B.sample 6
  • C.Error
  • D.Garbage value

Answer: C

Correct answer: Error

argv[1], argv[2] and argv[3] are char * values - addresses, not numbers - and C does not define addition between two pointers. The compiler rejects the expression.

The mistake is a common one, and it rests on forgetting that everything arriving on the command line is text. To get 6 the program would need to convert each string with atoi or strtol first, and only then add the resulting integers.

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

Post your comment

Please log in or register to post a comment.