"michael" <sp**@begone.netwrote in message
news:46**********************@per-qv1-newsreader-01.iinet.net.au...
: Hi All,
:
: I have the following:
:
: const int LENGTH = 5;
:
: void limitNameLength(string inText, char *&outText, int outLength){
You can have char* outText - no need to make it a reference
since the function does not change the pointer address itself.
: if(static_cast<int>(inText.length()) outLength){
: inText = inText.substr(0, outLength);
: }
: strcpy(outText, inText.c_str());
: if(static_cast<int>(strlen(outText)) < outLength){
: for(int i = strlen(outText); i < outLength; i++){
: outText[i] = ' ';
: }
: }
All of the previous can be simply written as:
void limitNameLength( string const& inText
, char *outText, int const outLength)
{
strncpy( outText, inText.c_str(), outLength );
//NB: if outLength<inText.size(), there will be no final '\0'
: outText[outLength] = static_cast<char>(NULL);
why not just: '\0' ?
This effectively relies on outText having a length
of outLength+1 !
: }
:
: int main(){
: char *temp;
: string name = "some long name";
:
: temp = new char[LENGTH];
: cout << "before : " << name << "\n";
: limitNameLength(name, temp, LENGTH);
: cout << "after : " << temp << "\n";
:
: delete [] temp;
: return 0;
: }
:
: if I comment out the call to limitNameLength the delete [] works ok.
If I
: don't the delete [] never returns.....
: Can anyone tell me why? As far as I can see all I have done is pass
the
: array to another function to manipulate it a bit then delete it. Why
does
: delete not work?
When you allocate an array of size LENGTH, the valid indices
are 0 .. LENGTH-1. limitNameLength writes over outText[LENGTH].
The buffer provided to limitNameLength needs to have 1 more character
than the requested maximum length of the string.
If outLength is to be the maximum buffer size, you could change
the last line to:
outText[outLength-1] = '\0';
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <
http://www.brainbench.com