C Programming - Command Line Arguments - Discussion


What will be the output of the program (sample.c) given below if it is executed from the command line?
cmd> sample friday tuesday sunday

/* sample.c */

int main(int sizeofargv, char *argv[])
        printf("%s", argv[--sizeofargv]);
    return 0;

[A]. sample friday tuesday sunday
[B]. sample friday tuesday
[C]. sunday tuesday friday sample
[D]. sunday tuesday friday

Answer: Option C


No answer description available for this question.

Balaji M said: (Dec 10, 2010)  
I need explanation regarding your answer.

Pandi said: (Dec 17, 2010)  
pls tell me about the detailed answer

Arvind said: (Feb 22, 2011)  
The first parameter inside main() contains the number of command line arguments. so sizeofargv = 4.
The second parameter inside main() contains the command line arguments as an array of string. so
*argv[3] = sunday
*argv[2] = tuesday
*argv[1] = friday
*argv[0] = sample

Mani said: (Jun 23, 2011)  
Thanks Arvind.

Prudhvi said: (Jul 20, 2011)  
Here sample is name of the program how can be it be an argument ?

Yogesh said: (Aug 27, 2011)  
The first parameter inside main(....)determines the number of cmd line arguments i.e sizeofargv=4.
and second parameter stores the actual parameters in array
argv[3] = sunday
argv[2] = tuesday
argv[1] = friday
argv[0] = sample

while loop executed four times. It breaks when value of sizeofargv becomes -1.
in first execution: argv[3]=sunday
in second execution: argv[2] =tuesday
in third execution: argv[1]=friday
in fourth execution argv[0]=sample
now value of sizeofargv becomes -1 and loop breaks.

Ferissa said: (Sep 12, 2011)  
Hi pruthvi this is ferissa, I think there is no error when the program name matches with the argument.

Narmada said: (Nov 2, 2011)  
Pruthvi in c for command line arguments the program name will be consider as first argument as argv[0]. So sample will be stored in argv[0].

Prakash said: (Dec 10, 2011)  
Great yogesh.....

Jyotir Mishra said: (Jun 27, 2017)  
Hello friends.

I think the result will be some how like.

"sunday, tuesday friday sample mainProgram" bcz total no of argument is 5 not 4
sizeofargv=5 because. the first index of argv[] will point to the main program itself.
i.e ---->
argv[4] = sunday
argv[3] = tuesday
argv[2] = friday
argv[1] = sample
argv[0]---- main program.

Vishal said: (Jul 21, 2017)  
@Jyotir Mishra.

The "sample" is the name of the program. So the number of arguments is 4 not 5.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.