Pointer Arithmetic data types

Posted on 2006-11-16
Last Modified: 2010-04-01
While I don't know if it is ANSI specified, I've seen before a data type which represents the difference or sum between two pointers, and I've heard it recommended that if you ever do pointer arithmetic, you cast the result to the appropriate data type.

This may be compiler specific, I'm not sure if the pointer arithmetic data type is defined in the standard.  But regardless, can anyone tell me what this pointer-arithmetic data type is called?  (I've seen it before, but now the name of the data type completely eludes me, and I can't find it on google.)
Question by:chsalvia
  • 2
  • 2

Expert Comment

ID: 17957508
Pointer arithmetic is not a separate data type. Pointer arithmetic are some arithmetic operations that can be done with pointers:

1.) Adding int to a pointer:
If you have pointer to some data type for example:

int* ptr;

and some int value i
then expression

*(ptr + i) is same as ptr[i].

In other words if you add integer (i) to a pointer (ptr), you will get a pointer to a place a memory i positions from ptr.

The same goes with subtraction.

      |   int1              |    int 2             |   int 3           |  int 4            |
      ^                                                                   ^
      ptr                                                                 ptr+3

2.) Subtracting to pointers:
To subtract two pointers, they must be same type.
For example:

double *ptr1, *ptr2;

then ptr2-ptr1 is an int value which represent number of positions between these two pointers.

      |   double 1   |    double 2     |   double 3     |  double 4        |
      ^                                                               ^
      ptr1                                                         ptr2

      ptr2 - ptr1 = 3!

In previous explanation, when I say position I think of number of bytes that given data type ocypies.

3.) ptr++; and ++ptr;
    Have same effect on ptr like ptr = ptr+1;
    Same thing with ptr--; and --ptr;

4.) Two pointers can't be added, multiplied, divided,...

5.) Poiner arithmetics is alternative way for accessing elements of an static or dynamicly allocated array:
For example:

int a[100];
int* b = new int[100];

then you can access i-th element of a with both: a[i] and *(a+i).
then you can access i-th element of b with both: b[i] and *(b+i).    

note that a+i and b+i are addresess of i-th element in arrays a and b respectivly.

I hope, I have been helpful.
Sorry, for my awkward english. :-)
LVL 16

Accepted Solution

imladris earned 125 total points
ID: 17957857
From MSDN:

Subtraction of Pointer Types
If both operands are pointers, the result of subtraction is the difference (in array elements) between the operands. The subtraction expression yields a signed integral result of type ptrdiff_t (defined in the standard include file STDDEF.H).

One of the operands can be of integral type, as long as it is the second operand. The result of the subtraction is of the same type as the original pointer. The value of the subtraction is a pointer to the (n – i)th array element, where n is the element pointed to by the original pointer and i is the integral value of the second operand.

So, ptrdiff_t is what I think you were looking for.

Expert Comment

ID: 17966482
Here is an example of using Pointer Arithmetic. As I have already said only correct operations with pointers are:

(Pointer Arithmetic Operations)

1.) adding an integer to pointer.
2.) subtracting an integer from a pointer.
3.) increment of pointer.
4.) decrement of pointer.
5.) subtracting an pointer from other pointer of same type.

6.) other operations with pointers like adding two pointers,
    multiplying or dividing two pointers dont make sense,
    and there fore are not supported.

Sample program:

Write program, which repeat following routine until user enters an incorect size of array.
 * asks for array size.
 * reads elements of array.
 * finds min and max element of array.
 * prints difference of indexes between max and min element (maxind - minind).
you are allowed only to use pointer arithmetic. :-)

#include <iostream>
using namespace std;

int main() {
      int *a, n;

      while (true) {
            // Asking for array size, allocating array, and filling
            // it with elements. Escaping the loop if array size is
            // an incorect value.
            cout << "Number of elements? ";
            cin >> n;
            if (n <= 0) break;
            a = new int[n];
            cout << "Elements? ";
            for (int i = 0; i < n; i++)
                  cin >> *(a+i);
            // pmin and pmax are pointers to integer type.
            // at the beggining they point at the first
            // element of array (beggining of array).
            // As you can see *(a+i) is i-th element of array
            // a (equivalent to a[i]), while a+i is address of
            // i-th element of array a (equivalent of &a[i]).
            // After executing next loop pmin and pmax point
            // to smallest and largest element of array a
            // respectivly.

            int *pmin, *pmax;
            pmin = pmax = a;
            for (int i = 0; i < n; i++) {
                  if (*(a+i) < *pmin)
                        pmin = a+i;
                  if (*(a+i) > *pmax)
                        pmax = a+i;
            // Now we print value of minimal and maximal element.
            // and the difference in their indexes (pmin-pmax), for
            // exampe if pax points to 8th element and pmin points
            // to 3th element, the difference is 5.

            cout << "min element: " << *pmin << endl;
            cout << "max element: " << *pmax << endl;
            cout << "difference in positions (indexes): " << pmax - pmin << endl;
            cout << endl;
            // Finally we are deallocating the memory we took for our array.            

            delete[] a;

Note that we could obtain the index of minimal element with:

int minind = pmin - a;

and similary the index of maximal element with:

int maxind = pmax - a;

It is interesting that we could go through array without "loop variable" i,
(with using pointer arithmetic instead), so part of code for finding pointers to
smallest and largest element could be changed with this code:

int *pmin, *pmax;
pmin = pmax = a;
for (int* t = a+1; t < a+n; t++) {
      if (*t < *pmin)
            pmin = t;
      if (*t > *pmax)
            pmax = t;

So now we are using pointer to integer as a loop variable and by incrementing
it we can travel through array and search for min and max element.

To sum up, pointer arithmetic is an usefull feature of C and C++ language, which can
be used as an alternative notation instead of "array indexing notation.

I hope, this is better and clearer answer than my previous.
LVL 16

Expert Comment

ID: 17980296
Did any of that clarify the matter for you?

If so, it is now time to select an answer and grade it.

If not, perhaps a clarifying question might help.

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Fully specialized class template function 21 146
Writing a parser for java language 4 91
c++ syntax question 9 57
trigs fail! I thought I knew how to do trignometry 3 82
Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question