C Programming - Command Line Arguments - Discussion

Discussion Forum : Command Line Arguments - Find Output of Program (Q.No. 3)
3.
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;
}
6
sample 6
Error
Garbage value
Answer: Option
Explanation:

Here argv[1], argv[2] and argv[3] are string type. We have to convert the string to integer type before perform arithmetic operation.

Example: j = atoi(argv[1]) + atoi(argv[2]) + atoi(argv[3]);

Discussion:
14 comments Page 2 of 2.

The prodigy said:   1 decade ago
The command line arguments are taken as strings (char *) and not integers.

Bhagat singh said:   1 decade ago
argv[3] is not declare automatically
so we never used argv[3]

Brindha said:   1 decade ago
Instead of arg[1] atoi(arg[1]) is to be put.

argv[1] will contain "1" (as string), we have to convert into integer with atoi() function.

Ranjit Singh said:   1 decade ago
Can any describe it how the error will generate?


Post your comments here:

Your comments will be displayed after verification.