#include <iostream>
usingnamespace std;
struct character
{
int age;
char gender;
char *name;
};
int main()
{
character *hero;
hero = new character;
hero->age = 20;
hero->gender = 'M';
hero->name = "David";
delete hero;
system("pause");
return 0;
}
is it safe to create a pointer to a struct that has a pointer as a member and then delete it? I'm asking this because I'm not allocating any memory to the pointer "name". won't it cause some memory leak, even after deleting "hero"?
With char pointers you shouldn't really have to allocate any memory if you're hardcoding a value like that to it, however if it's anything else you'll have to.
I'm agreeing with LB here, you should use std::string.
Try something like this. Just remember, you must be careful while dealing with pointers, because they need to be allocated and deallocated. In my example below, i've done it inside its constructor//destructor. Regarding to your crash, it is because you're trying to point to a literal instead of a pointer. That's why we use here "strcpy".
On line 21, you change the name pointer from pointing to the block of 64 characters to instead pointing to the string literal "David". You have a memory leak and then you try to call delete[] on the string literal, which crashes your program.
C-style strings are the absolute most horrible thing to learn this early in C++. Postpone your learning of them for a year or two. They're almost never used in C++.
As I said before, bufige's memory allocation is unnecessary. Simply assign it to "David" without deleting it. It isn't required to allocate memory dynamically here.
Indeed it is. But what the OP wants to learn how to deal with pointers,most probably, to reuse them somewhere. That's what i think from it's first post, and that is what i'm trying to point him.
thanks, guys :)
thank you bufige for showing me how to do it.
thank all of you for advising me to use string
I guess I have to wait until I learn more about C for this kind of stuff
and that's not gonna happen in the near future
I'll just use string afterall ^_^