Reputation: 501
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.
Upvotes: 8
Views: 10259
Reputation: 213810
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'
.Upvotes: 5
Reputation: 11706
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'
.
Upvotes: 12