Pointer arithmetic

Is pointer offset notation; pointer arithmetic?
Yes?
Is that a yes? I'm just checking, scared shitless is why. ( ,_,)
Yes. Also check this out:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main()
{
    const int ia[] = {0, 1, 2, 3, 4};
    const int *pi = ia;

    std::clog << pi[2] << '\n';
    std::clog << *(pi + 2) << '\n';
    std::clog << *(2 + pi) << '\n';
    std::clog << 2[pi] << '\n';
}

What's std::clog?

How does 2[pi] work?
std::clog is just like std::cout, but intended for logging.
http://cplusplus.com/reference/iostream/clog/

How does 2[pi] work?

What do you mean?
@Catfish4:
In that context 2 is not a pointer, neither has a pointer type assigned to it.
I assume it doesn't work, but I also assume you wanted to show the op it doesn't work straight-away.

@zero117:

To make 2[pi] work, it will become:

((int *)(2))[pi]

The reason why it works is:
Let's examinate this code snip:
1
2
3
int Data[] = { 0, 1, 2, 3, 4 };
int * pi = Data;
cout << pi[2];


What is written is "2".
It's the third element in the array.
Its location, in your RAM, is:
(pi + 2)
So, to access it you can do pi[2].
But also *(pi+2).

Due to mathematical rules, you will also be able to do
*(2+pi)

And
((int *)(2))[pi]
is equivalent to
*(2+pi)
@EssGeEich:
cl of VS2012 compiles the 2[pi] without warning and the output is same as for the other three.

http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Farsubex.htm
By definition, the expression a[b] is equivalent to the expression *((a) + (b)), and, because addition is associative, it is also equivalent to b[a]. Between expressions a and b, one must be a pointer to a type T, and the other must have integral or enumeration type. The result of an array subscript is an lvalue.
Didn't know.
Learnin' every day.
Topic archived. No new replies allowed.