C Programming - Command Line Arguments - Discussion

Discussion Forum : Command Line Arguments - Find Output of Program (Q.No. 19)
19.
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 */
#include<stdio.h>

int main(int argc, char *argv[])
{
    printf("%c", *++argv[2] );
    return 0;
}
s
f
u
r
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
25 comments Page 2 of 3.

Paras Vanika said:   1 decade ago
*++argv[2];

We can write this statement *++ *(argv+2);
Now it points to the *++(tuesday) ;

The ++ operator help to increase 1 character and now points to the u address.

*Help the char at this address that is u.

Suman Devi said:   1 decade ago
Shouldn't ++argv[2] be equivalent to a shift in the pointer by sizeof(char *)i.e. it should now be argv[3] and after dereferncing, it prints the first character of 4rth argument?

Pankaj kumar singh said:   1 decade ago
The answer is you but, I the explanation is not correct because sample is prog name and the arguments are friday[0] tuesday[1] and sunday[2] so you belongs from sunday.

Neha said:   1 decade ago
Command-line arguments are given after the name of a program in command-line operating systems like DOS or Linux, and are passed in to the program from the operating system.

To use command line arguments in your program, you must first understand the full declaration of the main function, which previously has accepted no arguments. In fact, main can actually accept two arguments: one argument is number of command line arguments, and the other argument is a full list of all of the command line arguments.

Sarfaraz Ahamad said:   1 decade ago
argv[0]=sample
argv[1]=friday
argv[2]=tuesday

Here it points to "tuesday"
By default array will start from zero and by (++) controll shift at one possition so it already holds the char 'u' thats why answer will be 'u'.

Preethi Ginimav said:   1 decade ago
@Sushma Thanks for explanation

Shrikant said:   1 decade ago
argv[0]=sample
argv[1]=friday
argv[2]=tuesday

Here we have printf("%c", *++argv[2] );

argv[2] pointed to the "tuesday" and argv is contains the address of first location and ++ operator is adding two byte(because of int) in argv then it takes the address of next location(u) and * operator is use for printing the value of that location;

Alok said:   1 decade ago
Can anybody explain ? How it's(*++argv[2]) pointing to 'U' ?

Sumit said:   1 decade ago
in *++argv[2]
argv[0]=t
argv[1]=u
argv[2]=e

Then whats is the answer.

Yuva said:   1 decade ago
Thanks sushma sister


Post your comments here:

Your comments will be displayed after verification.