pointer arithmetic: *p++ and (*p)++ and more

#include<stdio.h>
int main()
{
    int k=0;
    int* p=&k;
    printf("%d %d\n", p, k);
    *p++;
    printf("%d %d\n", p, k);
    (*p)++;
    printf("%d %d\n", p, k);
}

The code above prints this in Dev C++:

6422184 0

6422188 0

6412189 0 // p is increased 1 -> ???

The code above prints this in ideone.com:

368737692 0

368737696 0

368737696 0

#include<stdio.h>
int main()
{
    int k=0;
    int* p=&k;
    int* t=p; // the only difference
    printf("%d %d\n", p, k);
    *p++;
    printf("%d %d\n", p, k);
    (*p)++;
    printf("%d %d\n", p, k);
}

The code above prints this in Dev C++:

6422180 0

6422184 0

6412184 0

I think (*p)++ increases the value of the variable p is pointing. So I believe the first code should print this in Dev C++:

6422184 0

6422188 0

6412188 0

Does the existence of int* t affect the way (*p)++ works? Or is this just a kind of undefined behavior? I am weak about pointer, please help!

2 answers

  • answered 2017-06-17 18:14 Cioaca Radu

    Hello I've have finally understand your question and I think I have an explanation for it.

        #include<stdio.h>
            int main()
            {
                int k=0;
                int* p=&k; // p will point to k ( p -> k)
    
                printf("%d %d\n", p, k); // you will print p(k address) and k value
    
                *p++; // you increment p value so p NO LONGER points to k !!! 
    
                // p now holds another memory address (it is not related to k anymore)
    
                printf("%d %d\n", p, k); // you print the new p value and k value
    
                (*p)++; // here happens UNDEFINED BEHAVIOR
                //you increment a value and you  know nothing about it 
                // is it an int ? is it a char ? is it p adress itself ? ... ???
    
                printf("%d %d\n", p, k); 
            }
    

    I've tried your code on more compilers and I got different results(even on gcc under Ubuntu),too. Hope this helps, thanks.

  • answered 2017-06-17 18:14 Chris Dodd

    You start with p pointing a k, a local scalar variable which is a single int. You then increment p. Since k is not an array, incrementing p results in an invalid pointer (not pointing at anything), and then dereferencing it results in undefined behavior.

    Undefined Behavior means that ANYTHING might happen. Anything. While you might think that reading through the incremented pointer will just give you whatever happens to be in memory after k, there's no guarentee that will happen. The compiler is free to produce code that actually changes the values of unrelated things (like the value of p) for what appears to be a simple read that can't change the value of anything.

    In your case you actually modify (increment) the value pointed at be the invalid pointer, so its even more likely to cause strange and unpredictable results -- like munging the value of p