Click to See Complete Forum and Search --> : new in a class (for string)


remo
April 20th, 1999, 08:13 AM
Please help me!!

How can i make a string in a class dynamicly.
i want to put the input from the keyboard in a TempString and search the StringTerminator to build the dynamic string in the class. pleas help!!

I tried to make it but it return every time:

sizeof(CharArray) == 4

// Define Class

class TestClass
{
private:
char *CharArray;
public:
void Set_CharArray(char* Temp);
void Get_CharArray();

TestClass (int Size);
~TestClass ();
};

// define Methode

void TestClass::Set_CharArray(char* Temp)
{
strcpy(CharArray,Temp);
}

void TestClass::Get_CharArray()
{
cout<<sizeof(CharArray)<<endl;
cout<<CharArray<<endl;
}

// Define Constructor

TestClass::TestClass(int Size)
{
CharArray = new char [Size+1];
CharArray[0]='\0';
cout<<sizeof(CharArray)<<endl;
}

// Define Destructor

TestClass::~TestClass()
{
delete CharArray;
}

Paul McKenzie
April 20th, 1999, 10:20 AM
Simple. What is CharArray declared as? It's a *pointer* to a char. Guess what sizeof(char *) gets you? Answer -- 4.

What you need is the length of the string using strlen(), or better yet, use a C++ string class. In the latter case, you don't worry about allocating or deallocating memory.

Regards,

Paul McKenzie