gabi939
gabi939

Reputation: 107

Pointers arithmetic

I did a recursion exercise and I could not understand what is the difference between doing *p++ or *p+=1.

Both of them should add 1 to the value pointed at but for some reason *p+=1 works and *p++ doesn't.

void rec(char a[], int *p ,int i)
{
    if(a[i+1]== '\0')
        return;

    if(a[i]==a[i+1])
        *p+=1;

    rec(a, p, i+1);
}


void rec(char a[], int *p ,int i)
{
    if(a[i+1]== '\0')
        return;

    if(a[i]==a[i+1])
        *p++;

    rec(a, p, i+1);
}

Upvotes: 1

Views: 128

Answers (2)

user2736738
user2736738

Reputation: 30926

Precedence wise

++ > * > +=

Here *p+=1 is increasing the value that is pointed by p. Here the value at the memory location pointed by p is incremented. You can see the change in your code.

In the second case, *p++ it is just increasing the pointer p and then it de-references the value but you don't assign that r-value anywhere. This is not changing the actual content that there is in the memory pointed by p.

That is why in second case you don't see any change in the working variables and concluded that it doesn't work which is certainly not the case.

Upvotes: 1

haccks
haccks

Reputation: 106012

*p += 1; means, dereference the pointer p and then increment the dereferenced value by 1. While *p++; means

*p;
p += 1; // Increment the pointer itself  

This is because ++ has higher precedence than * operator so compiler will parse it as *(p++);.

(*p)++ is equivalent to *p += 1;.

Upvotes: 1

Related Questions