-1

Here is a sample

#include<stdio.h>

int main()
{
    char *c,d;
    char *p=&d,**z=&c,*u[2];
    printf("%d%8d%8d\n",(p),p+1,++p);
}

The output is showing as:

PS C:\Users\HOME\Desktop\New folder> .\a.exe
6422212 6422213 6422212

Since the value of p+1 is different but ++p is showing the same address i.e 6422212 instead of 6422213.The concept of pointer is totally new to me plz help me.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
Soumyadip
  • 7
  • 3
  • 3
    You are hitting undefined behavior – Daniel A. White Jul 30 '22 at 14:44
  • Apparently, in this particular implementation, for that line, `++p` is evaluated first. So, if your `p` is `6422211`, then it first increases to `6422212`, before the program tries to do `printf("%d%8d%8d\n",(p),p+1,p);}` – qrsngky Jul 30 '22 at 14:46
  • 1
    This other thread is about "undefined behavior" when dealing with increment operators: https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior – qrsngky Jul 30 '22 at 14:50

1 Answers1

0

You are getting unpredictable results because

  • You are reading and writing to p where there's no guarantee about the order.
  • You are using %d for a pointer.

These are undefined behaviour.

Fix these bugs and you get the expected results.

#include <stdio.h>

int main( void ) {
   char d;
   char *p = &d;
   printf( "%p\n", (void *)p       );  // 0x7fffc0e34fa0
   printf( "%p\n", (void *)( p+1 ) );  // 0x7fffc0e34fa1
   printf( "%p\n", (void *)++p     );  // 0x7fffc0e34fa1
   printf( "%p\n", (void *)p       );  // 0x7fffc0e34fa1
}

Demo on Compiler Explorer

ikegami
  • 367,544
  • 15
  • 269
  • 518