Search code examples
c++classpointersdynamic-allocation

Passing character pointers into a function and dynamically allocating memory


Student.h

class Student
{
 private:
      char m_sHouse[64];
 public:
 Student(void);
 ~Student(void);
 void getHouse(char *hName);
 void setHouse(char *hName);
}

Student.cpp

 void Student::setHouse(char *hName)
 {
    strcpy(m_sHouse, hName);
 }

 void Student::getHouse(char *hName)
 {
     if (m_sHouse != NULL)
     {
        hName = new char[strlen(m_sHouse)+1];
        strcpy(hName, m_sHouse);
     }
 }

In main:

 student.getHouse(house);
 if (strcmp(house, "house") == 0)
     cout <<"\tCorrectly returned the student house: " << house<< endl;

setHouse(char *hName) sets student->m_sHouse equal to "house".

My question:

When inside getHouse(char *hName), it acts as it should, setting hName to "house". but when control is passed out of the function, my dynamically allocated memory is deallocated, so when I strcmp in main, my program crashes (I end up comparing a NULL pointer).


Solution

  • Nick, the proper solution is that you know that hName is already allocated by the user of the class (Dr. Coleman). You simply need to strcpy into the character array.

    Simply put:

    void Student::getHouse(char *hName)
    {
      strcpy(hName, m_sHouse);
    }