Values to heap question

Pages: 12
Hi, i´m Faurax and I got two questions about writing to ram/buffer/memory.

The lower lines of integers and a string is a small part of all values I
need to have global in a little text-based game in Console mode.
I need them to be accessable from whatever dokument I´m writing.
It´s one document for each adventure in the game.
I have written two functions (not completed of course) in a c++ file.
The first function loads all needed strings and integers with values
for the game character, and the other saves it to the same file.

My first question is: How do I make or convert all my strings and integers
to the buffer memory so that I can check them later on in the game?

My other question is: How do I access the strings and integers values from the
memory when I need them?

I am using Dev c++ version 4.9.9.2 by the way.
My operative system is: Win XP SP3.
I´m new to c++ and therefore, i´m not so skilled in this subject.


1
2
3
4
5
string name;            // Declarates the string "name"
int moneycurrent;       // The current money you holds
int strength;           // Physical strength in battle
int power;              // Magical power in battle
int speed;              // physical and magical speed in battle 
Last edited on
You say you are new to C++. What programming languages are you most familiar with?
I´m a 3d designer who wants to learn more about coding. I have just tried a few scripts in Java and visual basic before. Just simple scripts, nothing advanced.
closed account (zb0S216C)
Values to heap question

So you want to allocate an object on the heap instead of the stack?

This can be done with the following example code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main( )
{
    // [ TYPE-IDENTIFIER ] *[ IDENTIFIER ];
    int *Allocator( NULL );

    // To allocate a single object:
    Allocator = new int( 0 );

    // To allocate an array of objects:
    Allocator = new int[ 3 ];

    // To delete allocated memory, you use the "delete" keyword, depending on the type of object you allocated:
    
    // If you allocated a single object:
    delete Allocator;
    Allocator = NULL;

    // If you allocated an array of objects:
    delete [ ] Allocator;
    Allocator = NULL;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int health;
int *HEAPhealth;

int main()
{
health = 150;

int MaxSize;
MaxSize = 10000;

        HEAPhealth = new int[MaxSize];
            HEAPhealth = NULL;

    cout << "Health: " << health << endl;
    cout << "Health from heap: " << HEAPhealth << endl;

delete HEAPhealth;
system("pause");
}


Okay, so now I have this code.
health has the value of 150 and
HEAPhealth has the value of 0.

How can I make the "HEAPhealth" get it´s value from "health"?
If I just do this change:

 
HEAPhealth = NULL;

to

 
HEAPhealth = health;


The error message is: invalid conversion from `int' to `int*'
Last edited on
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.
multiple definition of `my_var_1'
first defined here 
multiple definition of `my_var_2' 
first defined here


Thats the error message I get from the compiler if I let several .cpp files use the same header file.

By the way, can a header file hold the current value of a variable, string, integer etc.
Here is an example to show you what I mean.

test.h
 
int health;


main.cpp
1
2
3
#include "test.h"

health = 1;


other.cpp
1
2
3
#include "test.h"

health = health + 1;


Does the header included in both the .cpp files actualy hold the current value of int health or does "other.cpp" just import the declaration from test.h and not the value "1" "main.cpp" made it to?
Last edited on
I'm not sure that terminology is entirely correct, however, if you declare a variable in a header and then give it a value in one source file, it will have that value in all source files where the header is included., So in answer to your final question, yes, the value will be 'shared' across all the files.

I imagine these errors are because you are not only declaring but also initializing your variables in the header, i.e. you are doing this:
int var = 1;
rather than this
int var;
You shouldn't initialize variables in headers in most circumstances.

Hope this helps.
Thanks for the answers!
I did not know that values can be shared between several .cpp files just by including a header file with the values in it.
I thougt that a header file´s declared values can´t be changed from the outside of the header file itself.

One more question: is there a code or something to fix this error?
"multiple definition of `health'"

Any idés?

The full source codes is:

vars.h
1
2
3
#include <string>

int health;


main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "vars.h"
#include <iostream>

using namespace std;

int other();

int main()
{
health = 1;
other();
return 0;
}


other.cpp
1
2
3
4
5
6
7
8
9
10
11
#include "vars.h"
#include <iostream>

using namespace std;

int other()
{
health = health + 1;
cout << health << endl;
system("pause");
}
Last edited on
Ok. I'm sorry I think I made a mistake earlier and explained something wrong. You are only allowed to have one variable/funcion etc. of a particular name, and what I told you to do broke this rule. So ignore my earlier explanation. Really sorry about that :(

I'll try to re-explain as best I can, but perhaps someone else can do a better job.

In the header file, you need to write
extern int my_var_1;
This doesn't actually do anything with the variable, but merely tells the compiler that this variable may be used and it should look elsewhere for its definition.

Then you can declare and initialize it as normal in some source file which includes the header.
1
2
3
#include "vars.h"
// etc
int var = 4;


But you should be able to use it in any source file including the header, without redefining it.

Hope this is more helpful this time, and sorry again for accidentally giving you misleading information before.
Okay, I changed it and now it works.
Thank you for explaining that, you saved me a lot of time!
Last edited on
No problem. However, as I said I think some of the earlier stuff I said is not actually correct - I didn't think about everything carefully enough before posting (sorry again...). Anyway, the point is that perhaps you should try and find a resource somewhere on the internet and read up about this to get a more reliable insight into it all.
Is it possible for extern to handle strings?
Cause when I try, the compiler gets an error.
extern string name;

Error message:
`string' does not name a type

I see it works with "char" and "int" but is there a good way to do it with strings?

I don´t want to convert them forward and backward between char and string every
time I use them.
Last edited on
1
2
3
4
#include <string>

extern std::string name;
       std::string name;
Thanks, it worked!
@Caligulaminus: I'm sorry I don't follow. Why have you declared the variable as an external in the same file as you declared it normally?

@Faurax: The problem was merely that string is in the std namespace. You probably got used to just writing string because of your line using namespace std;. But of course, this line is not in the header (and if I were you I wouldn't use it in the header - just write 'std::string' in full there!).

is there a good way to do it with strings

Hopefully you now understand why your previous code wasn't working. Thus you can do it in the same way for strings as ints and chars, etc. In fact you can do it in that way for any type.

Hope this helps.
Okay, now I think I understad the logic behind it!
@Xander314: It's not necessary. I just amended Faurax' snippet to make it work.
But if you have the extern type var;in a header, something like that can happen. I think every compiler would accept it.
Is there a similar way to use an integer instead of string in this case?
getline(infile, stringName);

Cause I have a lot of lines that looks like this, just to have it working.
1
2
3
4
5
6
7
int moneycurrent;
string TEMP_moneycurrent;

getline(infile, TEMP_moneycurrent);

stringstream ss3 (TEMP_moneycurrent);
ss3 >> moneycurrent;
Last edited on
@Caligulaminus Fair enough. I was aware it was permissible since as you say it can turn up. I was just curious why you had done it because I'm not very experienced with external variables and I thought you might know something I didn't.
Pages: 12