Hi all,!'m new to the c++ programming scene and I'm trying to get to grips with pointers.
Lets say I have the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
struct player
{
char *name;
};
void main()
{
player *warrior;
warrior = new player;
warrior->name = newchar[20];
warrior->name = "CPP Noob";
delete warrior;
}
When I delete warrior, does it also deallocate the memory I allocated for player->name, or do I have to deallocate that to? I've tried delete player->name but that causes the program to crash.
The first line creates a new array of 20 chars and assigns its address (i.e. the address of the first element of the array) to warrior->name.
The second line assigns the address of the string literal "CPP Noob" to warrior->name. Oops you just lost the address of the newly created array above... This is called a memory leak. What you should do is replace that second line with strcpy(warrior->name,"CPP Noob");. This actually copies characters, it doesn't do an address assignment.
When I delete warrior, does it also deallocate the memory I allocated for player->name, or do I have to deallocate that to?
No, it doesn't. Yes, you have to deallocate that too. Before deleting warrior do something like:
delete[] warrior->name;.
To sum up, your program should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
struct player
{
char *name;
};
void main()
{
player *warrior;
warrior = new player;
warrior->name = newchar[20];
strcpy(warrior->name,"CPP Noob");
//kill some monsters here...
delete[] warrior->name;
delete warrior;
}
operator >> of cin is designed to do what you want here. However this method skips stops when it encounters space characters (i.e. spaces, tabs, newlines). Also it is not guaranteed that the user will not try to enter more than 20 characters and in that case you have a problem. I suggest doing it like this instead: