C++ sample interview question string copy function
- 2020-04-02 02:04:16
- OfStack
#include<iostream>
using namespace std;
//String copy function
char * sCpy(char *strDest, char *strSource)
{
_ASSERT((strDest != NULL) && (strSource!=NULL));
char *d = strDest; //Gets the current position of dest
char *s = strSource; //Gets the current location of the source
while ((*d++ = *s++) != '0') //Loop until you reach the last digit
{
}
*d = '0'; //Make up the last bit
return strDest;
}
int main()
{
char *strSource = "hello,world";
char *strDest = new char[strlen(strSource)+1]; //Note that the return length of the strlen function does not include '0', so add 1
_ASSERT(strDest != NULL);
char *strReturn = sCpy(strDest,strSource);
cout<<" Parameter returns a value "<<strDest<<endl;
cout<<" Function return value "<<strReturn<<endl;
//It should be ok not to release, the system will recover the resource after the main thread exits
delete strSource,strDest,strReturn;
strSource = strDest = strReturn = NULL;
return 0;
}
The strcpy(str1,str2) function copies the contents of str2 to str1, why do you need the return value of the function? Should be convenient to implement chain expression, such as:
Int i_length = strlen (strcpy (str1, str2));