c style pointer arithmetic?
Hi
Could somebody explain why the following 2 lines in the code below
1 2
|
cout << 2[arr] << "\n";
cout << 2[p1] << "\n";
|
are valid?
I understand all the other uses of pointers, but not the above 2.
Full code is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
#include <iostream>
using namespace std;
int main() {
int *p, i;
i = 10;
{
int i = 5;
int *p = &i;
std::cout << "p " << *p << "\n";
}
std::cout << "Before assignment \n";
p = &i;
std::cout << "After assignment " << *p << "\n";
int arr[] = {1, 2, 3, 4, 5};
int *p1 = arr;
cout << p1[2] << "\n";
cout << 2[p1] << "\n";
cout << *(p1 + 2) << "\n";
cout << arr[2] << "\n";
cout << 2[arr] << "\n";
cout << *(arr + 2) << "\n";
return 0;
}
|
2[arr] is just the same as
arr[2].
|
arr[2] = *(arr + 2) = *(2 + arr) = 2[arr]
|
Last edited on
Topic archived. No new replies allowed.