What will be the output of the program (myprog.c) given below if it is executed from the command line?
cmd> myprog friday tuesday sunday
/* myprog.c */
#include<stdio.h>
int main(int argc, char *argv[])
{ printf("%c", *++argv[1]); return 0; }
I understand argv[1] will be friday and ++argv[1] means tuesday. I might be wrong. Either way, I don't seem to understand what will be the meaning of the whole expression.
argv[1] indicates the first argument passed to the program, argv[2] the second argument, and so on.
The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element.
argc stands for argument count and argv stands for argument values. These are variables passed to the main function when it starts executing. When we run a program we can give arguments to that program like − $ ./a.out hello.
First, as a parameter declaration, char **argv is the same as char *argv[] ; they both imply a pointer to (an array or set of one or more possible) pointer(s) to strings.
Following operator precedence rules, the expression is equivalent to *(++(argv[1]))
. In other words, argv[1]
is evaluated first, which references the string "friday"
. Next, the ++
prefix increment changes the reference to the string "riday"
. Finally, the *
dereference returns the character 'r'
.
------------------------------
| f | r | i | d | a | y | \0 |
------------------------------
^ ^
| |
| ++argv[1]
|
argv[1]
Ergo, *++argv[1]
gives you the character ++argv[1]
points to, which is 'r'
. Demo.
What will be the output of the program (myprog.c) given below if it is executed from the command line?
It is terribly hard to learn programming without access to a computer with a compiler on it. What did it output when you executed the program?
Anyway...
argv[0]
is a pointer to a string containing the program name and the following arguments are pointers to the other command line parameters. argv[1]
is a pointer pointing to the string "friday"
, or rather to the first element 'f'
.++argv[1]
increments this pointer by 1, making it point at 'r'
instead. (Btw that code line is bad practice and poor programming style. Not only because it is hard to read, but also because it is generally a bad idea to alter the command line parameters.)'r'
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With