Implementation of strcpy (), implementation of strcpy ()
I can see a blog that is more in-depth than what I usually understand. mark: Implementation of the strcpy Function
Here, we only understand what we usually understand. There are three key points:
1 // strcpy implement 2 3 char * strcpy (char * dest, const char * src) 4 {5 assert (dest! = NULL & src! = NULL); // judge the validity of the parameter 6 char * ret = dest; // record the original target address, returns 7 while (* dest ++ = * src ++ )! = '\ 0') // first copy the data, and then judge whether the end is 8; 9 return ret; 10}
Why is char * returned?
A: it supports chained expressions, such as int len = strlen (strcpy (strA, strB ));
How can the strcpy prototype be implemented?
Char * strcpy (char * strDest, const char * strSrc); // if the second parameter is set to a constant, you do not want to change it in the middle of the function.
{
Assert (strDest! = NULL) & (strSrc! = NULL); // This sentence is an error that the asserted judgment should not have occurred.
// If a crop occurs, immediately stop it here
Char * address = strDest; // create an address pointer for returning
While (* strDest ++ = * strSrc ++ )! = '\ 0') // 2 points
// This sentence is complicated.
// (* StrDest ++ = * strSrc ++) This is a bitwise value assignment.
* StrDest is used after each assignment! = '/0': The comparison ends as a loop condition, that is, strSrc has been copied to the end.
Return address; // The last response.
}
Implementation of strcpy
Memset (dest, 0, sizeof (dest) in the main function and strcpy ));
This sentence has a problem;
Because char * dest does not point to any variable and the length is uncertain, the size of the allocated memory is also uncertain, so it is possible to access the allocation unit.
You can write it as memset (dest, 0, sizeof (src). This statement is a unit of the same size as dest and src. This is because when src is passed in strcpy, or the src in the main function is of a known size.