Firstly, with regard to your original post, it is possible to share variables between functions without using the heap. Consider this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
/********** variable declarations header: "vars.h" **************/
#include <string>
int my_var_1;
std::string my_var_2;
/************* source file "main.cpp" ******************/
#include "vars.h"
my_var_1 = 2;
my_var_2 = std::string("Hello World!");
int main()
{
// blah
return 0;
}
/*************** source file "other.cpp" ******************/
#include "vars.h"
void do_stuff()
{
my_var_1 = 3; // we can access this variable because you have included the header "vars.h"
}
You can also pass variables as function parameters.
Secondly, with regard to your above source code.
This line:
[code]int* HEAPhealth
| |
declares a
pointer to (i.e. memory address of) an integer, rather than an integer itself.
Hence,
HEAPhealth = NULL
is acceptable: a 'null' pointer, i.e. a pointer pointing to nothing.
On the other hand, since
health
is an
int
,
HEAPhealth = health
means you are trying to put a value of type
int
into a variable of type
int*
, i.e. int pointer.
What you want is this:
*HEAPhealth = health
. What this does is "dereference" the pointer HEAPhealth and actually put the value of
health
into the memory location given by your pointer.
Other than this, I can see some other important problems with your code.
Firstly, I'm not quite sure what you think
HEAPhealth = new int[MaxSize];
does. However, what it actually does is allocate heap memory for MaxSize integers. To allocate memory for a single integer, use
HEAPhealth = new int;
.
Note that the line
HEAPhealth = 0;
currently sets the
pointer to zero (as I explained above). This means that you are 'losing track' of all the memory you allocated, a so called memory leak.
Note that then if
delete
were used on HEAPhealth, which is now zero, you would get a runtime error.
Anyway, this is very longwinded and probably doesn't explain everything too well. Therefore, I suggest you think about this, correct your source code to the best of your ability and then repost it so I can see you got the right idea.
Hope this helps.