user1495306
user1495306

Reputation: 131

incrementing pointers in c

#include<stdio.h>

int main()
{
    int a=5,*b,*c;

    b=&a;
    c=b;

    *b++=*c++;

    printf(" %d %d %d\n",&a,b,c);
} 

Here if adress of a is x, then value of b and c is both becoming x+4. But shouldn't two ++ operator increase atleast one value by 8

Upvotes: 0

Views: 171

Answers (3)

Kundan Negi
Kundan Negi

Reputation: 41

Please keep this in mind

*b++ this means that b is pointing to some integer and that integer value is being incrmented by 1 not by 2 as it might appear to you with two + signs.And if you want to print pointers, you should use %p format specifier for that rather than using int.

Upvotes: -1

paddy
paddy

Reputation: 63461

You should use %p to format a pointer value, not %d.

All you are doing here is setting the value of a to itself via pointers. Beware that both b and c may not be dereferenced after being incremented (because they point to a single value, not an array).

Note that if you want to increment the actual value, you must use parentheses:

(*b)++;

That will dereference b and increment the value. If you do it without parentheses then it will increment the pointer and then dereference the original value.

Upvotes: 0

Peter Ruderman
Peter Ruderman

Reputation: 12485

No. Don't confuse the value of a pointer with the value that it points to.

The expression *b++ means: retrieve the value that b points to, and then increment the value of b.

Upvotes: 4

Related Questions