简体   繁体   中英

difference in incrementing pointer with ** and without in C

I've got an issue in understanding the difference in this two ways of incrementing pointers :

int **a;

a++;      //works fine
**a++;    //same here
a += n;   //still good
**a += n; //is not the same and I can't figure out what is going on

I was trying to print parameters of the program in reverse order here

int main(int argc, char **argv)
{
    argv += argc;                 //works fine until it is changed to 
                                  //                   **argv += argc
    while (--argc > 0)
    {
        argv--;
        (*argv)--;
        while (*(*argv)++)
            ft_putchar(**argv);
        if (argc - 1 > 0)
            ft_putchar('\n');
    }
    return (1);
}

Summing the question - why the second way is not working the same?

What I think is confusing you:

**a++ is parsed as **(a++) while
**a += n is parsed as (**a) += n

This is due to operator precedence

My advice is to always use parenthesis in cases like this to avoid any confusion.

Now on to each case:

Case 1

a++

Pointer arithmetic. Post-increments a

Case 2

**a++

is parsed as **(a++)

  • it post increments a - Pointer arithmetic
  • the result of evaluating (a++) is a - the value before the increment
  • then you have a double indirection.

So the above is equivalent (more or less) with the following:

**a;
a = a + 1;

Case 3

a += n

Pointer arithmetic. I would expect self-explanatory.

Case 4

**a += n

This is parsed as

(**a) += n

So you do a double indirection on a getting the value of the pointed integer and then you increase that integer (integer arithmetic).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM