Pointer arithmetic

May 10, 2013 at 8:17pm
Is pointer offset notation; pointer arithmetic?
May 10, 2013 at 8:22pm
Yes?
May 10, 2013 at 8:24pm
Is that a yes? I'm just checking, scared shitless is why. ( ,_,)
May 10, 2013 at 8:25pm
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';
}

May 10, 2013 at 8:36pm
What's std::clog?

How does 2[pi] work?
May 10, 2013 at 8:51pm
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?
May 10, 2013 at 8:58pm
@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)
May 10, 2013 at 9:23pm
@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.
May 10, 2013 at 9:40pm
May 11, 2013 at 12:10am
Didn't know.
Learnin' every day.
Topic archived. No new replies allowed.