Pointer arithmetic trickinessThis tip submitted by vishesh jain on 2005-05-05 06:18:01. It has been viewed 24595 times.
Rating of 6.0 with 97 votes
Remember that pointer arithmetic changes the value of the pointer with respect to the size of the base type so that every time you add 1 to a pointer, you are actually increasing its size by the actual size of the underlying type. For instance,
int *x = &y;
cout<<x<<" is not "<<x + 1<<" minus one";
The only time when adding one to a pointer is guaranteed to produce the exact next byte is when you perform pointer arithmetic on chars. This can be useful if you have a block of memory and want to treat it as a block of bytes. To access a particular byte, just cast the memory to a char before performing any pointer arithmetic.
Help your fellow programmers! Add a tip!