0

Output of C++ code

Can someone please explain this C++ code? #include <iostream> using namespace std; int main() { int t[4] = {8,4,2,1}; int *p1 = t+2; int *p2 = p1-1; p1++; cout << *p1 << endl; cout << *p2 << endl; cout << p1 << endl; cout << p2 << endl; cout << p1-p2 << endl; //why is this 2? Is this compiler dependent? cout << *p1 - t[p1-p2] << endl; return 0; }

30th Mar 2021, 6:37 PM
Edward Finkelstein
Edward Finkelstein - avatar
2 odpowiedzi
+ 3
Considering that you have understood the rest of the output, p1 is pointing to 1 in the array and p2 is pointing to 4 in the array. So when you subtract the two addresses p1-p2 it basically tells you that how many steps is p2 away from p1. Now let us say that p1 is at address 2000 so p2 would be at 1992 considering integer takes 4 bytes. So basically you have to take the difference between the two and divide by the size of the integer. So 2000 - 1992 = 8 And 8/4 = 2 which is the output.
30th Mar 2021, 6:58 PM
Avinesh
Avinesh - avatar
+ 2
The difference of p1-p2 shows the result of pointer arithmetic. Although the addresses are 8 bytes apart they are two integers apart, so the *pointer* difference is 2. Pointer arithmetic is compiler-independent.
30th Mar 2021, 7:15 PM
Brian
Brian - avatar