0

So, i am a student still learning about programming. As i was learning i came across a pointer program that had pre and post increment. When i executed the program i was a bit confused.

Code

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

Output

20
20
146459356

20
146459360 /* this output */
146459360

21
21
146459356 /* and this */

So, how did the *p after post increment display a garbage value and why did p show address of a after pre increment? Or is there any fault of the compiler? I use Ubuntu 16.04. Detailed answer would be appreciated. Thank you.

EsmaeelE
  • 2,331
  • 6
  • 22
  • 31
  • `Dereferencing an allocated memory invokes undefined behavior.` Very interesting and I would even say a revolutionary theory. @haccks – 0___________ Aug 19 '17 at 19:23
  • @PeterJ; OK. It should be **unallocated**. – haccks Aug 19 '17 at 19:26
  • 1. Dereferencing an unallocated memory invokes undefined behavior. In your program after `*p++;` dereferencing `p` will invoke this behavior. 2. Using wrong format specification for a data type also results in UB. Correct format for pointer data type is `%p`. 3. Signature of main should be `int main(void)`. – haccks Aug 19 '17 at 19:27
  • ... and `#include`s are a necessary part of **any** [mcve]. But the main question of yours is perfectly addressed in the duplicate target. – Antti Haapala -- Слава Україні Aug 19 '17 at 19:34

0 Answers0