jraavis

C Pointer Riddle

Jun 19th, 2017
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.82 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main() {
  4.     int a=2;
  5.     int *p=&a; /* *p = 1, p = 1004 */
  6.     printf("Line 1: %u %u\n",*p, p);
  7.     *p++;
  8.     /*
  9.     p++ = 1004 (incrementing p: operation not completed at)
  10.     *(p++) = increment'ing' p..! it's pointer, allotted with int 4bits again so *p = 1008
  11.     (==== it incrementing pointer not pointer pointing value. ====)
  12.     *p = 1008
  13.     */
  14.     printf("Line 3: %u %u\n",*p, p);
  15.     ++(*p);
  16.     /*
  17.     *p = 1008, p = 1008
  18.     *p p's pointer
  19.     p's incrementing p's pointer value, so p value (1008) added by 1.
  20.     so p = (p + 1); p = 1008+1; p = 1009 and *p some come with some new location 3001
  21.     */
  22.     printf("Line 4: %u %u\n",*p, p);
  23.     --p;
  24.     /*
  25.     (p = p-1) no more old pointer address but direct value.
  26.     p = 1009-4; p = 1005; and some new random p's address *p = 3420
  27.     */
  28.     printf("Line 5: %u %u\n",*p, p);
  29.     return 0;
  30. }
Add Comment
Please, Sign In to add comment