Is your basic C/C ++ skills solid?

Source: Internet
Author: User
Can we really write a strcpy function? We all think we can, but the strcpy we write may only get 2 out of 10 points. In this article, you can see examples of strcpy functions from 2 to 10 to see what level they belong. In addition, there are some interview questions to examine the examinee's agile thinking ability.
The analysis of these interview questions is very interesting. As a R & D personnel, the in-depth analysis of these interview questions can further enhance their internal strength.
1. Locate the wrong question
Question 1:
Void test1 ()
{
Char string [10];
Char * str1 = "0123456789 ";
Strcpy (string, str1 );
}
Question 2:
Void Test2 ()
{
Char string [10], str1 [10];
Int I;
For (I = 0; I <10; I ++)
{
Str1 = 'a ';
}
Strcpy (string, str1 );
}
Question 3:
Void test3 (char * str1)
{
Char string [10];
If (strlen (str1) <= 10)
{
Strcpy (string, str1 );
}
}
Answer:
Question 1 string str1 requires 11 bytes to be stored (including '\ 0' at the end), while string only has 10 bytes of space, strcpy will cause the array to cross-border;
For question 2, if the subject points out that the character array str1 cannot end in the array, it can give 3 points; if the subject points out strcpy (string,
Str1) The call makes the number of bytes copied from str1 [url =] memory [/url] to string memory uncertain. You can give 7 points, on this basis, it is pointed out that the strcpy method of the library function is given 10 points;
For question 3, if (strlen (str1) <= 10) should be changed to If (strlen (str1) <
10) because the strlen result does not count the 1 byte occupied by '\ 0.
Analysis:
Measure the test taker's knowledge about basic skills:
(1) The string ends with '\ 0;
(2) sensitivity to array out-of-bounds control;
(3) how the database function strcpy works. If the total score of a standard strcpy function is 10, the following are several different answers:
2. Compile a standard strcpy Function
2 points
Void strcpy (char * strdest, char * strsrc)
{
While (* strdest ++ = * strsrc ++ )! = '\ 0 ');
}
4 points
Void strcpy (char * strdest, const char * strsrc)
// Add the source string to const, indicating that it is an input parameter and adds 2 points
{
While (* strdest ++ = * strsrc ++ )! = '\ 0 ');
}
7 points
Void strcpy (char * strdest, const char * strsrc)
{
// Add non-0 assertions to the source and target addresses, and add 3 points
Assert (strdest! = NULL) & (strsrc! = NULL ));
While (* strdest ++ = * strsrc ++ )! = '\ 0 ');
}
10 points
// For chained operation, add 3 points to return the destination address!
Char * strcpy (char * strdest, const char * strsrc)
{
Assert (strdest! = NULL) & (strsrc! = NULL ));
Char * address = strdest;
While (* strdest ++ = * strsrc ++ )! = '\ 0 ');
Return address;
}
We can clearly see from two to ten answers that the little strcpy has hidden so many xuanjicang! What a solid basic skill is required to write a perfect strcpy!
(4) Master strlen, which does not include '\ 0' at the end of the string '.
After reading strcpy versions with different scores, you can write a strlen function with 10 points. The perfect version is:
Int strlen (const char * Str) // enter the const parameter.
{
Assert (strt! = NULL); // The asserted string address is not 0
Int Len;
While (* STR ++ )! = '\ 0 ')
{
Len ++;
}
Return Len;
}
Question 4:
Void getmemory (char * P)
{
P = (char *) malloc (100 );
}
Void test (void)
{
Char * STR = NULL;
Getmemory (STR );
Strcpy (STR, "Hello World ");
Printf (STR );
}
Question 5:
Char * getmemory (void)
{
Char P [] = "Hello World ";
Return P;
}
Void test (void)
{
Char * STR = NULL;
STR = getmemory ();
Printf (STR );
}
Question 6:
Void getmemory (char ** P, int num)
{
* P = (char *) malloc (Num );
}
Void test (void)
{
Char * STR = NULL;
Getmemory (& STR, 100 );
Strcpy (STR, "hello ");
Printf (STR );
}
Question 7:
Void test (void)
{
Char * STR = (char *) malloc (100 );
Strcpy (STR, "hello ");
Free (STR );
... // Other omitted statements
}
Answer:
Question 4: getmemory (char * P
) The parameter of the function is a string pointer. Modifying the parameter inside the function does not actually change the value of the input parameter.
Char * STR = NULL;
Getmemory (STR );
The subsequent STR is still NULL;
Question 5
Char P [] = "Hello World ";
Return P;
The P [] array is the partial automatic variable in the function. After the function returns, the memory has been released. This is a common mistake made by many programmers. Its root cause is that they do not understand the survival of variables.
Getmemory in question 6 avoids Question 4. The input parameter of getmemory is a pointer to the string pointer, but the request memory and value assignment statement are executed in getmemory.
* P = (char *) malloc (Num );
If the memory application is successful, add:
If (* P = NULL)
{
... // Handle the Memory Request failure
}
Question 7 has the same problem as question 6.
Char * STR = (char *) malloc (100 );
In addition, after free (STR), STR is not set to null, which may become a "wild" pointer. The following should be added:
STR = NULL;
In the test function of question 6, the memory of malloc is not released.
Analysis:
Question 4 ~ 7. Measure the test taker's understanding about memory operations. Generally, 50-50 of the respondents with solid basic skills can answer these questions correctly ~ 60 error. However, it is not easy to answer the correct questions completely.
The memory operations are mainly focused on:
(1) pointer understanding;
(2) The survival time and scope of the variable;
(3) good dynamic memory application and release habits.
Let's take a look at the following program errors:
Swap (int * P1, int * P2)
{
Int * P;
* P = * P1;
* P1 = * P2;
* P2 = * P;
}
In the swap function, P is a "wild" pointer, which may point to the system zone, causing program running to crash. An error "access" is prompted during debug running in VC ++
Violation ". The program should be changed:
Swap (int * P1, int * P2)
{
Int P;
P = * P1;
* P1 = * P2;
* P2 = P;
}
3. Internal issues
Question 1: Give the if
Statement (assuming the variable name is var)
Answer:
Boolean variable: If (! VaR)
Int type variable: If (Var = 0)
Float variables:
Const float epsinon = 0.00001;
If (x> =-epsinon) & (x <= epsinon)
Pointer variable: If (Var = NULL)
Analysis:
Evaluate the "internal function" of the 0 value. If (Var = 0) can be used to determine the value 0, and if (! VaR), pointer variable judgment can also be written as if (! VaR), although the program can run correctly, it cannot clearly express the meaning of the program.
Generally, If you want if to determine whether a variable is "true" or "false", you should directly use if (VAR), if (! VaR), indicating that it is a "logical" judgment. If you use if to judge a numeric variable (short, Int, long, etc.), you should use if (Var = 0 ), it indicates that it is compared with 0 on the "value", and the judgment pointer is suitable for using if (Var = NULL), which is a good programming habit.
Float variables are not accurate, so you cannot use "=" or "! = "To compare with a number, try to convert it to"> = "or" <=. If
(X = 0.0), the result is an error. The score is 0.
Question 2: The following is a 32-bit C ++ program under Windows NT. Calculate the sizeof value.
Void func (char STR [1, 100])
{
Sizeof (STR) =?
}
Void * P = malloc (100 );
Sizeof (p) =?
Answer:
Sizeof (STR) = 4
Sizeof (p) = 4
Analysis:
Func (char STR [2, 100]
) When the array name in the function is used as the function parameter, In the function body, the array name loses its meaning and is only a pointer, it also loses its constant feature and can perform auto-increment, auto-subtraction, and other operations and can be modified.
The essence of array names is as follows:
(1) The array name represents a data structure, which is an array;
For example:
Char STR [10];
Cout <sizeof (STR) <Endl;
The output is 10. Str indicates the data structure char [10].
(2) The array name can be converted to a pointer pointing to the object. It is a pointer constant and cannot be used for auto-increment, auto-subtraction, or other operations;
Char STR [10];
STR ++; // compilation error, prompting that STR is not the left Value
(3) When the array name is used as a function parameter, it becomes a common pointer.
On Windows NT 32-bit platform, the pointer length (memory size occupied) is 4 bytes, so sizeof (
Str), sizeof (p) are 4.
Question 3: write a "standard" macro min, which inputs two parameters and returns a smaller one. What will happen when you write the following code?
Least = min (* P ++, B );
Answer:
# Define min (A, B) (a) <= (B )? (A): (B ))
Min (* P ++, B) produces macro side effects
Analysis:
This interview mainly examines the use of the macro definition. The macro definition can implement functions similar to the function, but it is not a function, and the "parameter" in the arc of the macro definition is not a real parameter, during macro expansion, the "parameter" is replaced by one-to-one.
Programmers should be very careful with the use of macro definitions, and pay special attention to two problems:
(1) carefully enclose the "parameter" in the macro definition and the entire macro with an arc. Therefore, strictly speaking, the following answers:
# Define min (a, B) (a) <= (B )? (A): (B)
# Define min (a, B) (a <= B? A: B)
Both should be set to 0 points;
(2) Prevent the side effects of macros.
Macro definition # define min (A, B) (a) <= (B )? (A): (B) for Min (* P ++,
B) The result is:
(* P ++) <= (B )? (* P ++): (* P ++ ))
This expression produces side effects. The pointer P performs three ++ auto-increment operations.
In addition, the other answer that should be set to 0 is:
# Define min (A, B) (a) <= (B )? (A): (B ));
This answer is followed by the macro definition ";", indicating that the author's macro concept is vague and can only be ruthlessly scored 0 points and eliminated by the interviewer.
Supplement:
# What is the difference between include <FILENAME. h> and # include "filename. H?
A: For # include <FILENAME. h>, the compiler searches for filename. h from the standard library path.
For # include "filename. H", the compiler searches for filename. h from the user's working path.
Question 4: Why do standard header files have a structure similar to the following?
# Ifndef _ incvxworksh
# DEFINE _ incvxworksh
# Ifdef _ cplusplus
Extern "C "{
Related Article

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.