Original Post
🔒 Locked
Pointer arithmetic
Advertisement
Yes.
Quote:I'm not sure what you're refering to, why would it need to be stored somewhere else?
Original post by Muzlack
Is this memory stored somewhere completely different from the object itself so that pointer arithemetic can still work?
But yes, pointer arithmetic works just fine on heap allocated objects.
The pointer itself (which is 4 bytes [32-bits] on a 32-bit CPU), is on the stack. It points to the first byte of the object. The object can be stored anywhere, but with new it's stored on the heap. A double is 8 bytes long. So, if you have a pointer to a double, declared as double* pDouble, then double d = pDouble[1] means "Goto where pDouble is pointing, and move forward 1 object. Then move that object into 'd'". The compiler knows how far to move forward, because the type of pDouble is pointer to a double, and the compiler knows that a double is 8 bytes long. So the compiler moves 8 bytes forwards.
That answers my question then.
But if you did something like this:
(I just coded this right here, so it may be incorrect)
testArithmetic wouldn't point to test2, because the way I see it on the heap you would then have:
test1's integer pointer
test1's data x 50
test2's integer pointer
test2's data x 100
and since the pointer only knows the size of the pointer of the class, it would advance to the data, right?
Anyways, I'm just curious, thanks!
Bryce
But if you did something like this:
class example{private: int *p;public: example(int i);}example::example(int i){ //reserve i amount of integers *p = (int *) malloc (sizeof(int)*i);}int main(){ example *test1= new example(50); example *test2= new example(100); example *testArithmetic = test1; testArithmetic++;}(I just coded this right here, so it may be incorrect)
testArithmetic wouldn't point to test2, because the way I see it on the heap you would then have:
test1's integer pointer
test1's data x 50
test2's integer pointer
test2's data x 100
and since the pointer only knows the size of the pointer of the class, it would advance to the data, right?
Anyways, I'm just curious, thanks!
Bryce
It would point to garbage after that, since you delcare the two class variables
with two DISTINCT calls to new. Each Distinct call will grab a random slot from
memory that matches the requirements of the requested call, there is NO garateee
that they two calls right next to eachother in the code will give memory blocks
that are next to eachother.
with two DISTINCT calls to new. Each Distinct call will grab a random slot from
memory that matches the requirements of the requested call, there is NO garateee
that they two calls right next to eachother in the code will give memory blocks
that are next to eachother.
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement