Interview question: rewrite strcpy () function prototype)

Source: Internet
Author: User

It is known that the prototype of the strcpy function is

Char * strcpy (char * strdest, const char * strsrc );

1. Implement the strcpy function without calling the Library Function
2. Explain why char * is returned *;

1. Implementation Code of strcpy

Char * strcpy (char * strdest, const char * strsrc)
{
If (strdest = NULL) | (strsrc = NULL) // [1]
Throw "invalid arguments"; // [2]
Char * strdestcopy = strdest; // [3]
While (* strdest ++ = * strsrc ++ )! = '/0') // [4]
;
Return strdestcopy;
}

[1]

(A) The effectiveness of the pointer is not checked, indicating that the designer does not pay attention to program robustness.
(B) used to check the pointer validity ((! Strdest) | (! Strsrc) or (! (Strdest & strsrc), which indicates that there is no deep understanding of implicit type conversion in C language. In this example, char * is converted to bool as implicit type conversion. This function is flexible, however, this increases the error probability and maintenance costs.
(C) Use (strdest = 0) | (strsrc = 0) to check the pointer validity. This means that the respondent does not know the benefit of using constants. Directly Using a literal constant (such as 0 in this example) reduces the maintainability of the program. 0 is simple, but there may be a lot of pointer checks in the program. In case of PEN mistakes, the compiler cannot find that the generated program contains logical errors and it is difficult to eliminate them. If null is used to replace 0, the compiler will check if a spelling error occurs.
[2]

(A) return new string ("invalid arguments");, indicating that the respondent is not aware of the intended use of the response, and is not cautious about memory leakage, it is very dangerous to return the memory allocated to the function body from the function body. It throws the obligation to release the memory to an uninformed caller. In most cases, the caller will not release the memory, which leads to memory leakage.
(B) Return 0;, indicating that the respondent did not master the exception mechanism. The caller may forget to check the return value, and the caller may not be able to check the return value (see the chain expression below ). If you want the return value to shoulder the dual function of returning the correct value and abnormal value, the result is often invalid in both functions. The return value should be replaced by throwing an exception, which can reduce the burden on the caller, prevent errors from being ignored, and enhance the maintainability of the program.
[3]

(A) if you forget to save the original strdest value, it means that the answer provider's logic is not strict.
[4]

(A) cyclically write it as while (* strdest ++ = * strsrc ++);, same as [1] (B ).
(B) cyclically write while (* strsrc! = '/0') * strdest ++ = * strsrc ++;, indicating that the respondent does not check the boundary conditions effectively. After the loop body ends, '/0' is not correctly added to the end of the strdest string '.

2. Return the original strdest value to enable the function to support chained expressions, increasing the "added value" of the function ". Functions of the same function are naturally more ideal if they can reasonably improve availability. The form of a chained expression is as follows:
Int ilength = strlen (strcpy (stra, strb ));

Another example:
Char * stra = strcpy (New char [10], strb );

The original strsrc value is returned incorrectly. First, the source string must be known and it does not make sense to return it. Second, the expression in the second example cannot be supported. Third, to protect the source string, the const uses const to limit the content referred to by strsrc and returns const char * as char *. If the type is different, an error is returned during compilation.

 

Reprinted statement:
This article from http://blog.csdn.net/lxrm_fly/archive/2007/08/06/1728051.aspx

========================================================== ==============================================

Strcpy function prototype

 

 

Char * strcpy (char * strdest, const char * strsrc)
 
Char * strcpy (char * strdest, const char * strsrc)
{
If (strdest = NULL | strsrc = NULL)
Return NULL;
If (strdest = strsrc)
Return strdest;

Char * tempptr = strdest;
While (* strdest ++ = * strsrc ++ )! = '')
;
Return tempptr;
}

========================================================== ==============================================

About the '/0' string ending flag

 

Today, we see a statement like this:
While (* dData! = '/0') displayonechar_ LCD (x ++, Y, * dData ++ );

I have never used it before, nor have I ever seen this '/0'. intuitively, this'/0' should be used to determine whether the string array ends. However, I still don't know much about the principle, so I quickly went online to search. Now it is really good to have a network. You can find the answer to any problem on the Internet.

Originally, there was no special string variable in C language, and a character array is usually used to store a string. The string always uses '/0' as the end of the string.
. Therefore, when a string is saved to an array, the terminator '/0' is also saved to the array as a flag for whether the string ends. With the '/0' sign, you do not need to use the length of the character array to determine the length of the string.

'/0' indicates the end mark of the string.

For example, assign a string to an array:
U8 str1 [] = {"cxjr.21ic.org "};
In fact, the actual storage of the array str1 in the memory is:
C x j r. 2 1 I c. o r G'/0'
The '/0' after this is automatically added by the C compilation system. Therefore, when you use a string to assign an initial value, you do not need to specify the length of the array.
.
Copy the string in character array str1 to character array str2. The string end flag '/0' is also copied.

But ...... Some exceptions also occur.
For example, when the length of an array is insufficient. Suppose we specify the length of the array, for example:
U8 str1 [13] = {"cxjr.21ic.org "};
The length of str1 in the character group is 13, so the subsequent information is lost, that is, '/0.

In addition, when assigning values to an array, each character is enclosed in quotation marks. '/0' is also lost '. For example:
U8 str1 [] = {'C', 'x', 'J', 'R ','. ', '2', '1',' I ', 'C ','. ', 'O', 'R', 'G '};
If you want the array to end with '/0', it is either written:
U8 str1 [] = {"cxjr.21ic.org "};
Either write (manually add '/0 '):
U8 str1 [] = {'C', 'x', 'J', 'R ','. ', '2', '1',' I ', 'C ','. ', 'O', 'R', 'G','/0 '};
Either write (intentionally reserve a blank space for the array ):
U8 str1 [14] = {'C', 'x', 'J', 'R ','. ', '2', '1',' I ', 'C ','. ', 'O', 'R', 'G '};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.