Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 248
  • Last Modified:

Pointer Arithmetic data types

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.)
0
chsalvia
Asked:
chsalvia
  • 2
  • 2
1 Solution
 
UrosVidojevicCommented:
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. :-)
0
 
imladrisCommented:
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.
0
 
UrosVidojevicCommented:
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.
U.V.
0
 
imladrisCommented:
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.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now