* ++ argv [1] in C. What does this mean?

What will be the output of the program (myprog.c) 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 that argv [1] will be on Friday, and ++ argv [1] means Tuesday. I might be wrong. In any case, I do not seem to understand what will be the meaning of the whole expression.

+8
c pointers
source share
3 answers

Following the rules of operator precedence , the expression is equivalent to *(++(argv[1])) . In other words, argv[1] is evaluated first, which refers to the string "friday" . Then incrementing the prefix ++ changes the link to the string "riday" . Finally, the spread * returns the character 'r' .

+12
source share
 ------------------------------ | f | r | i | d | a | y | \0 | ------------------------------ ^ ^ | | | ++argv[1] | argv[1] 

Ergo, *++argv[1] gives you the character ++argv[1] , which is equal to 'r' . Demo

+9
source share

What will be the output of the program (myprog.c) below if it is executed from the command line?

It is extremely difficult to learn programming without access to a computer with a compiler. What did he output when running the program?

Anyway...

  • argv[0] is a pointer to a string containing the name of the program, and the following arguments are pointers to other command line parameters.
  • So, argv[1] is a pointer pointing to the string "friday" or, rather, to the first element of 'f' .
  • ++argv[1] increments this pointer by 1; instead, it points to 'r' . (By the way, this line of code is bad practice and a bad programming style. Not only because it is difficult to read, but also because it is usually difficult to change command line parameters.)
  • Taking the contents of a pointer should therefore give you an 'r' .
+4
source share

All Articles