0

This code is from MSDN (http://msdn.microsoft.com/en-us/library/6t4fe76c(v=VS.80).aspx).

#include <string.h>

class String {
public:
   String( char *ch );  // Declare constructor
   ~String();           //  and destructor.
private:
   char    *_text;
   size_t  sizeOfText;
};

// Define the constructor.
String::String( char *ch ) {
   sizeOfText = strlen( ch ) + 1;

   // Dynamically allocate the correct amount of memory.
   _text = new char[ sizeOfText ];

   // If the allocation succeeds, copy the initialization string.
   if( _text )
      strcpy_s( _text, sizeOfText, ch );
}

// Define the destructor.
String::~String() {
   // Deallocate the memory that was previously reserved
   //  for this string.
   if (_text)
      delete[] _text;
}

int main() {
   String str("The piper in the glen...");
}

Why the size of the dynamic array (_text) should be one unit more than "ch"?

sizeOfText = strlen( ch ) + 1;
_text = new char[ sizeOfText ];
strcpy_s( _text, sizeOfText, ch );
2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by hystaspes
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.