Addition of Two Pointers in C or C++ Not Supported. Why

Addition of two pointers in c or c++ not supported. why?

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.

Edit: To address the common wish for finding the mid consider this (purely as an example):

#include <stdio.h>
int main (int argc, char **argv){
int arr[] = {0,1,2,3,4,5,6,7,8,9};
int *ptr_begin = arr;
int *ptr_end = &arr[9];
int *ptr_mid = ptr_begin + (ptr_end - ptr_begin)/2;
printf("%d\n", *ptr_mid);
}

I am quite sure that you can always come up with an offset-computation which lets do what you want to achieve with addition.

Why can't I add pointers?

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.

Why Pointer+Pointer is not allowed but Pointer+integer allowed?

Think this way.

Address 1: 112, Bakers street
Address 2: 11, Nathan road

Why Address1 + 3 is fine but Address1 + Address2 is bad.

(BTW by Address1 + 3 I mean 115, Backers street)

For the same reason multiplication of scalar or an address to another address doesn't make sense.

address1 * 2 // Invalid
address1 * address2 // Invalid

Logically it is possibly to take an offset from an address by adding/subtracting but adding 2 addresses doesn't make sense because addresses of same variables may be different in each run of program. Moreover the type and value of addition don't make any sense.

I thought pointer + pointer is not allowed due to security reason.

No it is not allowed because addition of pointers does not make any sense.

if a pointer say p1 holds 66400 and p2 holds 66444. now
p1+p2 is not allowed but p1+66444 is allowed.

You are thinking only about values think of their types also. For example if a holds 2 kg, and b holds 3 meter, it does not make sense to add them.


There is one more important thing to learn from address analogy:

Let's say there are 80 houses on Nathan road (analogous to arrays in C) and if you add 70 to Address 2 you may land in a house, a garbage bag, or in the sea. For the same reason, if you go more than 1 past the address in array or address before the of array behaviour is undefined. If you dereference any address beyond the array, behaviour is undefined.

int NathanRoad[80] = {...};
int *address1 = &NathanRoad[11];
int *q;
int s;
q = address1 + 3; /* OK */
s = *(address1 + 3); /* OK */
q = address1 + 75; /* Bad */
q = address1 + 69; /* OK */
s = *(address1 + 69); /* Bad */

Pointer addition vs subtraction

The difference between two pointers means the number of elements of the type that would fit between the targets of the two pointers. The sum of two pointers means...er...nothing, which is why it isn't supported.

What is the rationale for limitations on pointer arithmetic or comparison?

There are architectures where program and data spaces are separated, and it's simply impossible to subtract two arbitrary pointers. A pointer to a function or to const static data will be in a completely different address space than a normal variable.

Even if you arbitrarily supplied a ranking between different address spaces, there's a possibility that the diff_t type would need to be a larger size. And the process of comparing or subtracting two pointers would be greatly complicated. That's a bad idea in a language that is designed for speed.

Adding pointer addresses - legality

The difference of two pointers (high - low) is an integer (actually ptrdiff_t, which is a signed integer type), so you're adding an integer to a pointer, which is perfectly legal. This also explains why it's perfectly OK to divide the difference by 2, which is not something you could do with a pointer.

Adding the values of two pointers and saving the addition into another pointer

You can't have a pointer depend on the values of multiple other pointers the way you want. But you could write a lambda that captures the dependent variables by reference, and returns the value returned by the call to foo. Any changes to the values pointed at by the pointers will be reflected in what the lambda returns. You'll need to use call syntax to access the value.

auto ab = [&] { return foo(a,b); };  // define ab

std::cout << ab() << std::endl; // use ab

Here's a demo.

What is the rationale of making subtraction of two pointers not related to the same array undefined behavior?

Speaking more academically: pointers are not numbers. They are pointers.

It is true that a pointer on your system is implemented as a numerical representation of an address-like representation of a location in some abstract kind of memory (probably a virtual, per-process memory space).

But C++ doesn't care about that. C++ wants you to think of pointers as post-its, as bookmarks, to specific objects. The numerical address values are just a side-effect. The only arithmetic that makes sense on a pointer is forwards and backwards through an array of objects; nothing else is philosophically meaningful.

This may seem pretty arcane and useless, but it's actually deliberate and useful. C++ doesn't want to constrain implementations to imbuing further meaning to practical, low-level computer properties that it cannot control. And, since there is no reason for it to do so (why would you want to do this?) it just says that the result is undefined.

In practice you may find that your subtraction works. However, compilers are extremely complicated and make great use of the standard's rules in order to generate the fastest code possible; that can and often will result in your program appearing to do strange things when you break the rules. Don't be too surprised if your pointer arithmetic operation is mangled when the compiler assumes that both the originating value and the result refer to the same array — an assumption that you violated.



Related Topics



Leave a reply



Submit