Does anyone have any good articles or explanations (blogs, examples) for pointer arithmetic? Figure the audience is a bunch of Java programmers learning C and C++.
Here is where I learned pointers: http://www.cplusplus.com/doc/tutorial/pointers.html
Once you understand pointers, pointer arithmetic is easy. The only difference between it and regular arithmetic is that the number you are adding to the pointer will be multiplied by the size of the type that the pointer is pointing to. For example, if you have a pointer to an int
and an int
's size is 4 bytes, (pointer_to_int + 4)
will evaluate to a memory address 16 bytes (4 ints) ahead.
So when you write
(a_pointer + a_number)
in pointer arithmetic, what's really happening is
(a_pointer + (a_number * sizeof(*a_pointer)))
in regular arithmetic.