0
Am i going about this right?
/* i know if i just threw his into a script it probably wouldnt work but am i on the right track?*/ #include <iostream> using namespace std; int main(){ //global vars_________________________________________ int x; int *xp *xp = &x; int lvl; int *Plvl; *Plvl = &lvl; int EHealth; int *PEHealth; PEHealth = &EHealth; int PHealth; int *PPHealth; *PPHealth = &PHealth;
2 Answers
+ 3
-You need a semicolon after int *xp.
-Instead of doing
int x;
int *xp;
*xp = &x;
Do:
int *xp = new int;
The above allocates memory for an integer, and stores the address in the xp pointer. (Note I did not say the *xp pointer - this is because *xp dereferences the xp pointer, and rather than signifying the pointer itself, signifies the value it points to.)
-This is why
*xp = &x;
is incorrect - you are setting the value that xp points to the address of x
-This is correct:
xp = &x;
-When your pointers become unnecessary:
delete randompointer;
Remember when we said that "new" allocates memory? "delete" frees that memory up so that it can be used again. (deallocation)
I apologize for my long winded explanation - I like to be a little too thorough. đ.
0
Aaand remember to delete every pointer you have created. E.g.:
delete xp;
Program cannot delete dynamic allocations, and if you won't delete pointer there's going to be memory leak.