Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address arithmetic

Consider the following piece of code :

int main() {    
    long long * x = new long long [10]; // array of long long
    long a = (long) x;  // address of first element
    long b = (long) (x+1); //address of second element
    long c = b - a ;  // first difference
    long d = (long) ((x+1) - x);  // second difference
    std::cout << c << std::endl ;
    std::cout << d << std::endl ;
    return 0;
}

The program out puts first 8, then 1 . I have got some understanding of pointers, and how to use them. I have come to the conclusion that adding +1 to a raw pointer value will increment it by the size of the thing it is pointing. This feature is unfamiliar to me.

So my question is why do pointer types behave like this? What would be the use of such behaviour ?

like image 539
Evdzhan Mustafa Avatar asked Mar 20 '26 22:03

Evdzhan Mustafa


1 Answers

Pointer arithmetic allows you to write code that processes an array. Consider summing an array of ints:

int values[] = { 0, 1, 2, 3};
int* current = values;
int* end = values + 4;
int sum = 0;
while (current != end)
{
    sum += *current;
    ++current;
}

Of course, there are easier ways to accomplish this than using raw pointers, so don't ever write code as complicated as this to do something that is simpler to do another way. As other answers have pointed out, array indexing is translated into pointer arithmetic by the compiler: values[2] is equivalent to saying *(values + 2) so in this case looping over the array with the much simpler code is what you should do.

for (int i = 0; i < 4; ++i)
{
    sum += values[i];
}

There are more advanced reasons to use pointer arithmetic because it can actually help to simplify implementation; for example I've used it before in an assignment along with reinterpret_cast to create a free list memory allocator.

like image 135
masrtis Avatar answered Mar 23 '26 12:03

masrtis