0

When I'm dereferencing and printing the output of a given array pointer, I'm getting my array in reverse. Here's the code

using namespace std;

int main()
{   
    int arr[5] = {1,2,3,4};
    int* ptr = arr;
    cout<<ptr<<endl;
    cout<<*ptr++<<endl;
    cout<<*ptr<<" "<<*ptr++<<" "<<*ptr++<<" "<<*ptr++;
    return 0;
}

Output

0x61fee8
1
0 4 3 2

But since I filled the array in increasing order and incremented the pointer I was expecting the output to be as 1 2 3 4

and why there is a zero in 2nd line?

Alpha
  • 88
  • 6
  • 1
    Does this answer your question? https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points – 463035818_is_not_an_ai Mar 08 '22 at 12:56
  • TL;DR Configure your compiler to use C++17, or split the last `cout` to separate statements. – HolyBlackCat Mar 08 '22 at 12:57
  • Does this answer your question? [Undefined behavior and sequence points](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – prapin Mar 08 '22 at 13:16

1 Answers1

1

The first thing to note is that the size of the array is 5 and the number of initialization elements is 4, which means that the last element will be initialized to 0.

The reason for unordered output is that C++ compiler does not guarantee the order in which the parameters of << are evaluated. It means that, in your last cout, it is possible that the third ptr++ is evaluated before the first one.

If you replace your last cout with multiple couts as follows, you will see that the code works as you expect.

cout<< *ptr;
cout<< *ptr++;
cout<< *ptr++;
cout<< *ptr++;
halfer
  • 19,824
  • 17
  • 99
  • 186
moriaz
  • 96
  • 6