I have this regular struct

struct Person{

  char *name;
  int age;

}

and I should do some regular stuff like, input size, create dynamic array of persons , and take user input for this person. But the problem, as you can see is how do I input in name pointer; I tried using buffer and simply pointing name to that buffer, yeah that works until buffer goes out of scope and destroys it self(at least I think he does..). Then I made global buffer and it works fine,but only for 1 person object, obviusly. Only soultion is to make global 2D dynamicly alocated char array in wich I will store inputs, and than use name pointer to point to them. That seems weird. Is there,and I hope that is some better way to do this. Reason why I don't use string or char array is because this is homework so I must use name pointer. Help me,please.

Every time you create a Person object, get some memory with new. Then name points at that memory.

You need to delete that memory at the right time. A good way to do this is to create a constructor and destructor for your struct. Something like this

struct Person{
  char *name;
  int age;

  Person(int size);
  ~Person();
}

Person::Person(int size)
{
  name = new char[size];

}

Person::~Person()
{
  delete[] name;
}

Take the input into a char buffer and then allocate and copy it to a new buffer, which you assign to the struct. Also, since this is C++, you need to create a default constructor which will null the pointer and set the age to some sane value, such as 0. Remember, structs in C++ are simply classes where the default for member variables and functions is public. Also, create a destructor that will de-allocate the name buffer, otherwise you will end up with a memory leak! And this is not getting near to the need to reference count links to the buffer if you assign it elsewhere! :-) Have fun!

yap, just created a dynamic array for every name pointer(for every person), and than copied a buffer into that array. I just have one more Q. In the begining I create Person dynamic array, so when I delete [] Person, do I delete those sub-arrays inside it or do I have to do that manualy also?

You need to call delete[] on every piece of memory you got with new []. One for one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.