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.

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'.

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.

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.

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?

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.

Balaji said:   1 decade ago
@Sumit: It will print null('\0') character. i.e. blank space will be printed.

Naga Vikas said:   1 decade ago
But in Dev C++, it is showing "r".

I guess it differs from compiler to compiler.

argv[0]--shows the path.

1-sample.
2-friday.
3-tuesday.
4-sunday.

argv[2]----friday.
++agrv[2] is pointing at "r".
*++argv[2]...prints the value r.

Manjunath(mj) said:   10 years ago
This will print s.

How it will print u friends please any one explain me?

Elayaraja said:   9 years ago
The Precedence of dereference operator(*) and increment operator(++) is same.So we see associativity of these operators is right to left.

*++argv[2];
argv[2] is Tuesday here argv is point to base address of "tuesday"

When we do increment it'll point to next location content 'u' since argv is a character pointer
now we do dereference of this operator. Then we'll get u.

Amol said:   8 years ago
Thanks @Sushma.
(1)


Post your comments here:

Your comments will be displayed after verification.