ABDUL HASEEB.
ABDUL HASEEB.

Reputation: 13

My value gets Wrong if I use ++ operand with my pointer

My Code is:

int abdul = 11;
    int *ptr = &abdul;
//Problem is here
//  *ptr += 1;
//  *ptr++;
    cout << &*ptr;
    cout << "\n" << &abdul;
    cout << *ptr;
}

If I use *ptr +=1 it added 1 in abdul location value. But if I use *ptr++ it gives some random value.

When I use *ptr += 1 the output is correct. But using increment or decrement operator value gets wrong. I don't know where the problem is.

Upvotes: 0

Views: 59

Answers (3)

Verthais
Verthais

Reputation: 447

Due to the Operator Precedense what happens is you increment the address doing ptr++ and then you dereference it by doing *ptr.

what you can do is use prefix increment : ++*ptr

Upvotes: 0

Lukas-T
Lukas-T

Reputation: 11370

Operator precendece. *ptr++ is evaluated as *(ptr++). But you want (*ptr)++ Just add some parantheses to show the compiler what you want.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206737

Due to operator precedence, *ptr++ is treated as *(ptr++). The pointer is incremented first and then dereferenced. In your case, that causes undefined behavior since ptr points to a single object.

To increment the value of the object that ptr points to, use (*ptr)++ or ++(*ptr).

It's better to be clear about your intention using parenthesis.

Upvotes: 5

Related Questions