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.

Siri said:   1 decade ago
Cmd line arguments passed is sample 1 2 3 (which is your filename followed by args).
==============================================.

argv[0]=> Contains your executable file name/ program name (in this case sample is the program name).

argv[1]=> Will have 1.

argv[2]=> Will have 2.

argv[3]=> Will have 3.

And all these will be stored in the form of strings. So to add convert the args to integer using atoi function and then add.

Abhishek sakariya said:   1 decade ago
I am focusing on Linux environment. Is it possible to write.

Char*argv instead of char**argv?

Yogesh said:   1 decade ago
But for me it prints the output as 1 use online C compiler from here.

Aadesh said:   10 years ago
@Abhishek.

You can use it if you want to pass a single argument in command line arguments. But generally we pass more than 1 so we need to take array of pointer to char.


Post your comments here:

Your comments will be displayed after verification.