Home > Back-end >  Questions about the string new and delete
Questions about the string new and delete

Time:09-28

Code as shown in figure, the functions are joining together two strings, I new a new space in a child function is used to store after mosaics of string, but there was a problem in the main function to delete, how should I ask you to delete right off the application of space?


CodePudding user response:

 
Char * stringcat (char * a1, char * a2)
{
Char * s3=new char [strlen (a1) + strlen (a2) + 1);
Char * temp=s3;
While (* a1! Temp++=='\ 0') {* * a1 + +; }
While (* a2! Temp++=='\ 0') * * a2 + +;
* temp++='\ 0';
Return the s3;

}
Int main (int arg c, char * argv [])
{
Char * t1="ABC";
Char * t2="123";
Char * tempstr;
Tempstr=stringcat (t1, t2);
Printf (" % s ", tempstr);
The delete [] tempstr;
getchar();
return 0;
}

CodePudding user response:

Remove the const

CodePudding user response:

You have a problem of algorithm, this sentence: s3 [I + 1)='\ 0';

CodePudding user response:

In local function declarations and new space, you should be in a local function release, suggested to:
Char * s;
Char * stringCat (const char * s1, s2 const char *)
{
S=new char [strlen (a1) + strlen (a2) + 1);
.
}
Int main (int arg c, char * argv [])
{
.
The delete [] s.
}

  • Related