1

When I initialize the constructor with the given data type of the parameter, I find that it goes wrong with the explaination that " const char* values cannot be assigned to char* entities".

class TString
{
private:
    char* m_pData;
    int  m_nLength;
public:
    TString();
    TString(const  char* pStr);
    ······
}
TString::TString(const  char* pStr) {
    this->m_pData = pStr;
}

What should I do to solve this problem? If possible, give me a right example. Thanks in advance and apolpgize for my ignorance.

trawolf
  • 13
  • 6

1 Answers1

1

Const char * generally are prefined static compiled strings that cannot be changed because they are locked in the source code, or they come from some immutable source. This is in part, why they are marked const to prevent people from trying to change them.

The easiest solution to this problem is to take the const char * and make a copy of it on the heap, then it is no longer constant.

For example:

#include <string.h> // for strdup
...
TString::TString(const  char* pStr) {
    m_pData = strdup(pStr); // this will malloc and copy the string accepting const char * as input.
}

One thing you will need to consider, the m_pData is now on the heap, so in the destructor, you will want to free this data otherwise you will have a memory leak.

TString::~TString(){
  free(m_pData);
}

You will also want in the TString() constructor to set the m_pData=NULL too.

This will work with strings, but if it's binary data i.e. no terminator allocate the data using malloc and use a memcpy, like:

m_pData=(char *)malloc(m_nlength*sizeof(char));
memcpy(m_pData,pStr,m_nlength);

Or some such.

Owl
  • 1,446
  • 14
  • 20