Allocating memory..

Started by
3 comments, last by asdfg__12 16 years, 9 months ago
Im having a little problem with this code :



vector2D *TEMP1 = new vector2D();
 *TEMP1 =  V1-V2; //v1 & v2 = vector struct
float x1 =  TEMP1.x;
float x2 = TEMP1.y;
delete vector2D;

Dev cpp returns this error:

  ~~path~~ `x' has not been declared 
  ~~path~~ `y' has not been declared 

But if i do this (i know its the bad way) :

vector2D TEMP1  =  vector2D(0,0);
 TEMP1=V1-V2;
float x1 =  TEMP1.x;
float x2 = TEMP1.y;

It works ! Any ideas what im doing wrong ? -.-!!
Advertisement
TEMP1 is a pointer. so to access member variables use the -> operator instead of the .

TEMP1->x;TEMP1->y;


remember that when using pointers, a pointer is not the object itself. It is literally a pointer to where the object lives in memory. the -> operator dereferences the pointer so what comes after it is what exists at the memory location held in the pointer.

[EDIT: for an object as small as a vector that 2nd option that you call "the bad way" is probably much more efficient. memory allocations to the heap are slow, a vector is small and so should have no problem fitting on the stack]

-me
delete vector2D;

should be...

delete TEMP1;

not sure why you are using new here....
what is wrong with

...
vector2D TEMP1 = V1-V2;
...
=Loren Tapia=
Quote:Original post by Palidine
TEMP1 is a pointer. so to access member variables use the -> operator instead of the .

*** Source Snippet Removed ***

remember that when using pointers, a pointer is not the object itself. It is literally a pointer to where the object lives in memory. the -> operator dereferences the pointer so what comes after it is what exists at the memory location held in the pointer.

-me


lol! , so simple !!
Thanks , that was quick :)

EDIT:

@Loren:
Thanks , it was just a stupid mistake while i was removing the big part of the function.. :)

Quote:
[EDIT: for an object as small as a vector that 2nd option that you call "the bad way" is probably much more efficient.


Hmm...even if your struct class uses operators ?

And just in case you didn't fully get it, TEMP->x is equivalent to (*TEMP).x

Quote:
@Loren:
Thanks , it was just a stupid mistake while i was removing the big part of the function.. :)

Quote:

[EDIT: for an object as small as a vector that 2nd option that you call "the bad way" is probably much more efficient.




Hmm...even if your struct class uses operators ?



Why do you say this? operators are just like any other function, it has nothing to do with whether you allocate statically or dynamically.

This topic is closed to new replies.

Advertisement