Why Can't I Add Pointers

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.

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 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 */

Why can't I assign values to pointers?

The easiest way to modify it is to create an array for your storage, and then copy the string into it.

For example:

char buf[128];
const char *src = "Hello World";
strncpy(buf, src, 127); // one less - we always 0-terminate
buf[127] = '\0';

// you can now modify buf
buf[0] = 'W';

The reason your code doesn't work is that you haven't allocated any memory for the copy of the string - you've just made a second pointer to the same read-only memory. (And then tried to copy it? I'm not quite sure what the rest of the code is doing.) You need to get some non-read-only memory somewhere, and it's much easier to use the standard library to copy it into that new memory, rather than writing the loop yourself.

In the case when you don't know the length of the string beforehand, you can also use malloc (or, even better, do what drschnz's answer says and use new char[]):

const char *src = "Hello world";
char *buf = malloc(strlen(src) + 1); // or = new char[strlen(src) + 1];
strcpy(buf, src);
// you can now modify buf
// later, you need to free it
free(buf); // or delete [] buf;

Also, if you're using C++, you can just use a std::string:

std::string myString("Hello world");
myString[0] = "W";

Hope that helps.

Why can't I access a pointer to pointer for a stack array?

Because test is not a pointer.

&test gets you a pointer to the array, of type char (*)[256], which is not compatible with char** (because an array is not a pointer). This results in undefined behavior.

std::string '+' : cannot add two pointers

There is no + operator to concatenate C strings. C strings are just pointers (const char *), so if you add a number to it, it will just increment that pointer. Afterwards you convert it to a C++ string:

std::string s = "aaa" + 1

|=======|
"aa"
const char *

|==============|
"aa"
std::string

Then in the second step it fails, when you try to concatenate the second string because while adding a constant to a pointer still made some sense (even though not in your case), there is no way you can make sense of adding two pointers.

"aaa" + 1 + "bbb" 

|========|
"aa"
const char *

|===|
const char *

To make sure you actually concatenate and don't sum pointers, I'd suggest using a stringstream. This also makes sure your constant number is converted properly to a string.

std::stringstream ss;
ss << "aaa" << 1 << "bbb";
std::string s = ss.str();

This will work for every type that has the operator<< overloaded.

In C, why can't you declare a pointer and make it point to a number directly, without malloc?

//X     
int num = 5;
int *ptr;
ptr = #

For the above, the int value "num" is allocated on stack, or in program data segment so it has an address. Lets pretend it was assigned by the compiler the address 0x12345678. You create an int* ptr. This also has address lets say 0x20000000. The address currently point to random data. We want to make the pointer at 0x20000000 point to the data value at 0x12345678, so that we can read the contents of 0x12345678 and get back the value 5... so we place 0x12345678 inside the storage space at 0x20000000 (we set ptr = &num).

//Z
int* myptr;
*myptr = 5;

For the second example, we only have 0x20000000 (myptr). Its a pointer and it currently pointing nowhere or anywhere. When we do *myptr = 5, we look at the address stored at 0x20000000. Its random so it may be 0xffff0000 lets use that example. It will then try and write the value 5 to this address (0xffff0000) which does not exist and causes the segfault.

So in your last example, the pointer exists, but it does not point anywhere valid, so when you try to write where it points, you either corrupt valid memory or cause a segment fault.

Can`t add pointer on object to the set

bool OBJECT::operator== (const OBJECT &object) const
{
return *this == object;
}

This function calls itself, causing a stack overflow. You should replace this function with whatever logic you want to use to tell if the two objects are equivalent.

Also, unless every OBJECT has a unique m_numberOfObject value, your operator< does not create a strict ordering. (Because neither of two objects with the same m_numberOfObject value but otherwise different will be less than the other.) This may cause your set to work differently from how you expect.



Related Topics



Leave a reply



Submit