C++ Pointers – Benefits of Incrementing Pointers

cpointers

I just recently started learning C++, and as most people (according to what I have been reading) I'm struggling with pointers.

Not in the traditional sense, I understand what they are, and why they are used, and how can they be useful, however I can't understand how incrementing pointers would be useful, can anyone provide an explanation of how incrementing a pointer is a useful concept and idiomatic C++?

This question came after I started reading the book A Tour of C++ by Bjarne Stroustrup, I was recommended this book, because I'm quite familiar with Java, and the guys over at Reddit told me that it would be a good 'switchover' book.

Best Answer

When you have an array, you can set up a pointer to point to an element of the array:

int a[10];
int *p = &a[0];

Here p points to the first element of a, which is a[0]. Now you can increment the pointer to point to the next element:

p++;

Now p points to the second element, a[1]. You can access the element here using *p. This is different from Java where you would have to use an integer index variable to access elements of an array.

Incrementing a pointer in C++ where that pointer does not point to an element of an array is undefined behaviour.

Related Topic