Search code examples
cpointersincrement

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?


Solution

  • 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).