Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I add pointers?

Tags:

c++

pointers

I have code very similiar to this:

LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator+(const Iterator& right)const
{
    return (this + &right);//IN THIS PLACE I'M GETTING AN ERROR
}

LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator-(const Iterator& right)const
{//substracts one iterator from another
    return (this - &right);//HERE EVERYTHING IS FINE
}

err msg: Error  1   error C2110: '+' : cannot add two pointers

Why I'm getting an error only in one place and not in both?

like image 380
There is nothing we can do Avatar asked May 29 '10 12:05

There is nothing we can do


People also ask

Why pointer addition is not possible?

Pointers contain addresses. Adding two addresses makes no sense because there is no idea what it would point to. Subtracting two addresses lets you compute the offset between the two addresses.

Is it possible to add pointers?

There is no possibility to add pointers together. Since pointer contains address details there is no way to retrieve the value from this operation.

Can we add two pointer variables in C?

Pointers contain addresses. Adding two addresses makes no sense, because you have no idea what you would point to. Subtracting two addresses lets you compute the offset between these two addresses, which may be very useful in some situations.


2 Answers

742 Evergreen Terrace + 1 = 743 Evergreen Terrace

742 Evergreen Terrace - 1 = 741 Evergreen Terrace

743 Evergreen Terrace - 741 Evergreen Terrace = 2

743 Evergreen Terrace + 741 Evergreen Terrace = ???

like image 103
fredoverflow Avatar answered Sep 26 '22 04:09

fredoverflow


Pointer addition is forbidden in C++, you can only subtract two pointers.

The reason for this is that subtracting two pointers gives a logically explainable result - the offset in memory between two pointers. Similarly, you can subtract or add an integral number to/from a pointer, which means "move the pointer up or down". Adding a pointer to a pointer is something which is hard to explain. What would the resulting pointner represent?

If by any chance you explicitly need a pointer to a place in memory whose address is the sum of some other two addresses, you can cast the two pointers to int, add ints, and cast back to a pointer. Remember though, that this solution needs huge care about the pointer arithmetic and is something you really should never do.

like image 44
Michał Trybus Avatar answered Sep 23 '22 04:09

Michał Trybus