CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 1999
    Posts
    12

    new in a class (for string)

    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;
    }


  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: new in a class (for string)

    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


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured