Solved

Pointer Arithmetic data types

Posted on 2006-11-16
4
236 Views
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.)
0
Comment
Question by:chsalvia
  • 2
  • 2
4 Comments
 
LVL 7

Expert Comment

by:UrosVidojevic
Comment Utility
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

by:
imladris earned 125 total points
Comment Utility
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

by:UrosVidojevic
Comment Utility
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

by:imladris
Comment Utility
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
TTimer no longer functioning 7 74
SetCurrentDirectory path limit 7 92
Dialogbox API leak? 18 57
FMX TCameraComponent Problem 2 8
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
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…

728 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now