October 22, 2024
Chicago 12, Melborne City, USA
C++

Why does a pointer to the first element of an array, after dereference, evaluates to the third element?


It dereferences to the third element when I’m trying to do it inside printf(), where I also try to dereference that pointer with post and pre-increment.

Here’s my code:

#include <stdio.h>
int main()
{                                                                                                                
    int arr[4] = {1, 2, 3, 4};
    int *ptr = &arr[0];
    
    printf("ptr = %p, &arr[0] = %p\n", ptr, &arr); // same addrs
    printf("*ptr = %d\n", *ptr); // 1, as expected

    // PROBLEM IS HERE:
    printf("%d, %d, %d\n", *ptr, *ptr++, *++ptr); // 3, 2, 2  

    return 0;
}

I’ve tried funny things like adding elements to an array, changing order of expressions in printf to,
but it gave me another confusing answer:

*++ptr, *ptr++, *ptr // 3, 1, 1

But, when I tried printfs in sequence, so to say:

printf("*ptr = %d\n", *ptr);
printf("*ptr++ = %d\n", *ptr++);
printf("*++ptr = %d\n", *++ptr);

Everything worked as expected.

What I expected from initial script in the last printf:

  1. *ptr = 1
    Obviously, because it’s the first element
  2. *ptr++ = 1
    Firstly we dereference, and only then post-increment does its’ thing
  3. *++ptr = 3
    After previous incremention we are at the second element, now pre-increment goes first, hence we are at the addr of the third element, and, well, dereference gives us 3 – the value of the third element.

So then, why did I got 3, 2, 2?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video