Solved

# Pointer Arithmetic data types

Posted on 2006-11-16
241 Views
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
Question by:chsalvia
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• Learn & ask questions
• 2
• 2

LVL 7

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. :-)
0

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.
0

LVL 7

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.
U.V.
0

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.
0

## Featured Post

Question has a verified solution.

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

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
###### Suggested Courses
Course of the Month3 days, 10 hours left to enroll

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

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