It''s soo cool that you can allocate an entire array of pointer objects, but I have one question about the process. When you allocate just one object like this...
balance *p;
p = new balance;
p->SomeFunctionIDidNotCreate();
delete p;
return(true);
it uses the arrow operator. However, if you allocate an array of objects like this...
balance *p
p = new balance [3];
p[0].SomeFunctionIDidNotCreate();
delete [] p;
return(true);
it uses the dot operator. I''m sure there is a valid reason, or is there?
JaRoS
p-> and p[0]. do exactly the same thing. I _mean exactly . So does (*p). for that matter, that ugly syntax is why -> was added to C. While we''re at it, 0[p]. also does the same thing
Let''s say we got s, an object, on the stack. And let''s ignore methods for now, and access a property.
struct MyStruct { int a; int b; };
MyStruct s; s.a = 1; //This takes the storage address s and slaps 0x0001 there.
s.b = 2; //This takes the storage address s, adds 4, and slaps a 0x0002 there. It adds 4 because a is 4 bytes big.
MyStruct p = new MyStruct; p->a = 1; //This takes the value stored at the address p, and uses it as an address, and slaps a 0x0001 there.
p->b = 2; //This takes the value stored at the address p, adds 4, and slaps a 0x0002 there.
p[0].a = 1; //This takes the value at address p, uses the value there as an address and slaps a 0x0001 there
p[1].b = 2; //This takes the vale at address p, uses the value there plus the sizeof(MyStruct)*1, and attemps to slap a 0x0002 there (we just wrote a bug).
When you use constants in the [] the compiler will calculate the needed offset - so if you use [0] it''s the same as using * And (*p). is the same as p->
C and C++ make no distinction between a pointer and an array. Some would say this is bad, that arrays are definetly different than pointer and should not be treated the same way. Other say that the need for -> and . to access method is overly complicated. Those that understand, understand that there isn''t a difference between a pointer and an array, and that whether it''s a . or a -> means something.
p[1].b = 2; //This takes the vale at address p, uses the value there plus the sizeof(MyStruct)*1, and attemps to slap a 0x0002 there (we just wrote a bug
a bug?
what is the size of (MyStruct)*1 anyway? Isnt it 8 bytes?
With your permission, GameDev.net uses analytics cookies to understand how people use the platform.
You can accept analytics or continue with necessary cookies only.
Learn more