Difference between *ptr += 1 and *ptr++ in C

前端 未结 5 663
星月不相逢
星月不相逢 2020-12-23 19:58

I just started to study C, and when doing one example about passing pointer to pointer as a function\'s parameter, I found a problem.

This is my sample code :

5条回答
  •  忘掉有多难
    2020-12-23 20:33

    Let's apply parentheses to show the order of operations

    a + b / c
    a + (b/c)
    

    Let's do it again with

    *ptr   += 1
    (*ptr) += 1
    

    And again with

    *ptr++
    *(ptr++)
    
    • In *ptr += 1, we increment the value of the variable our pointer points to.
    • In *ptr++, we increment the pointer after our entire statement (line of code) is done, and return a reference to the variable our pointer points to.

    The latter allows you to do things like:

    for(int i = 0; i < length; i++)
    {
        // Copy value from *src and store it in *dest
        *dest++ = *src++;
    
        // Keep in mind that the above is equivalent to
        *(dest++) = *(src++);
    }
    

    This is a common method used to copy a src array into another dest array.

提交回复
热议问题