Difference between ++*argv, *argv++, *(argv++) and

2019-03-04 06:40发布

Currently I am learning C and trying to get my head around these instructions. Are they actually different?

++*argv

*argv++

*(++argv)

*(argv++)

Thanks!

4条回答
一夜七次
2楼-- · 2019-03-04 07:22

Two small examples of incrementing.
Tip: For a better understanding, try to imagine argc as 1 or 2.

Post-increment

In the program below, all arguments are printed including the program name argv[0].

int
main(int argc, char **argv)
{
    while (argc--)
        printf("%s\n", *argv++); /* same as *(argv++) */
}

Pre-increment

In the program below, all arguments are printed except the program name argv[0].

int
main(int argc, char **argv)
{
    while (--argc)
        printf("%s\n", *(++argv));
}

++*argv increments the value *argv.

查看更多
beautiful°
3楼-- · 2019-03-04 07:26

When you are using pre increment and post increment operators ie ++argv and argv++ in assignments you have to know about the rvalue and lvlue.Like whether the variable value will be incremented first and then get assigned to the LHS or after assigning to LHS the variable value gets incremented.Also the bracket changes the precedence.SO the concepts precedence,lvalue and r value,and rules of pointer increment needs to be understood.

查看更多
4楼-- · 2019-03-04 07:37

Take a look at the below code.

main()
    {

       int a[4] = { 10,20,30,40};
       int *argv = a;
       t = ++*argv; 
       printf("%d\n",*argv); /* Here *argv is 11 */
        printf("%d\n",t); /* Here t is 11 because of pre-increment */

       *argv++; /* argv is incremented first ++ has higher priority over "*" */ 
       printf("%d\n",*argv);/* *argv is printed which is 20 */

       *(++argv); /* argv is incremented first ++ has higher priority over "*" */ 
       printf("%d\n",*argv); /* *argv is 30 */

       *(argv++); /* As explained above the same applies here also */
       printf("%d\n",*argv);
    }
查看更多
等我变得足够好
5楼-- · 2019-03-04 07:42

It's the postfix increment operator that has higher precedence than the pointer de-reference operator, not the prefix increment. So these two are equivalent:

*p++  *(p++)

The prefix increment has the same precedence as *, so *++p increments the pointer, and is the same as *(++p). Also, ++*p is the same as ++(*p).

查看更多
登录 后发表回答