Undefined behavior
Let's break it down:
int arr[5] = {8,2,9,4,5},a,b,*ptr;
int c = 5;
ptr = arr; // ptr = address of arr[0]
a = *ptr + 10; // a = (arr[0] + 10) = (8 + 10) = 18
ptr = &c; // ptr = address of c
ptr += 2; // UNDEFINED BEHAVIOR, c is not an array
cout<<*(ptr+1); // COULD PRINT ANYTHING
Not that we've established undefined behavior, the language lawyers can't sue me to explain what might be happening:
The variables of main
are possibly piled onto the stack as follows. It's convenient that the elements on the stack are integer for this simple example:
0x100 c
0x104 arr[0]
0x108 arr[1]
0x10C arr[2]
0x110 arr[3]
0x114 arr[4]
0x118 a
0x11C b
0x120 ptr // address of the variable ptr, not what ptr points to
Hence, ptr+2
is the same address as the arr[1] in the array, which holds a value of "2". And then then the additional (ptr+1)
expression is the address of arr[2], which holds the value 9.
But that's because you are getting lucky. Any other system or compiler could crash the program or make the lights dim in your house. Such is the nature of undefined behavior.