Reputation: 21
So, I was messing with pointers, and I've got confused with some things. First, let me start with a basic example which beahaves like expected:
void* h = new char[16] {}; //pointer to a array of char, 16 bytes, and initilizes with 0
int* o = (int*)h; //gets the adress of the first byte
*o = 16; //sets the value
std::cout << *(int*)h << std::endl; //Prints the memory value
std::cout << *o; //Prints the memory value
and It prints this:
16
16
But this one doesn't output what I think it would:
int* o = (int*)h+1; //gets the adress of the second byte
*o = 16; //sets the value
std::cout << *(int*)h+1 << std::endl; //Prints the memory value
std::cout << *o; //Prints the memory value
But it outputs:
1
16
Shouldn't the two numbers be 16? As far as I know, by adding value to the pointer it increments the memory in bytes. So, is there something that I'm missing here?
Upvotes: 1
Views: 208
Reputation: 98338
You have an issue with precedence of operators. Of all the operators you are using the highest precedence is that of the cast to (int*)
. So when you do (int*)h+1
you are actually doing ((int*)h)+1
, and that is not the pointer to the second byte, but a pointer to the second integer, that is you are advancing sizeof(int)
bytes.
Similarly with *(int*)h+1
you are actually doing (*(int*)h)+1
, that is you are reading the first integer (that would be 0
) and adding 1 to that integer (0 + 1 = 1
). In this case you are not doing pointer arithmetic.
If you want to do proper pointer arithmentic you need a few parenthesis, but note that you cannot portably do pointer arithmentic with void *
: use instead char *
Upvotes: 2