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

huy nguyen picture huy nguyen · Feb 10, 2016 · Viewed 17.3k times · Source

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 :

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int* allocateIntArray(int* ptr, int size){
    if (ptr != NULL){
        for (int i = 0; i < size; i++){
            ptr[i] = i;
        }
    }
    return ptr;
}

void increasePointer(int** ptr){
    if (ptr != NULL){
        *ptr += 1; /* <----------------------------- This is line 16 */
    }
}

int main()
{
    int* p1 = (int*)malloc(sizeof(int)* 10);
    allocateIntArray(p1, 10);

    for (int i = 0; i < 10; i++){
        printf("%d\n", p1[i]);
    }

    increasePointer(&p1);
    printf("%d\n", *p1);
    p1--;
    free(p1);
    fgets(string, sizeof(string), stdin);
    return 0;
}

The problem occurs in line 16, when I modify *ptr+=1 to *ptr++. The expected result should be the whole array and number 1 but when I use *ptr++ the result is 0.

Is there any diffirence between +=1 and ++? I thought that both of them are the same.

Answer

user3386109 picture user3386109 · Feb 10, 2016

The difference is due to operator precedence.

The post-increment operator ++ has higher precedence than the dereference operator *. So *ptr++ is equivalent to *(ptr++). In other words, the post increment modifies the pointer, not what it points to.

The assignment operator += has lower precedence than the dereference operator *, so *ptr+=1 is equivalent to (*ptr)+=1. In other words, the assignment operator modifies the value that the pointer points to, and does not change the pointer itself.