C ++ Test

Source: Internet
Author: User

2. 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 [I] = '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) calling makes the number of bytes replicated from the str1 memory to the string memory uncertain. It can be given 7 points. Based on this, it is pointed out that the strcpy function is working for 10 points;

For question 3, if (strlen (str1) <= 10) should be changed to if (strlen (str1) <10 ), the result of strlen 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 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:

In question 4, the form parameter of the GetMemory (char * p) function is a string pointer. Modifying the form parameter within the function does not actually change the value of the input form 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. In VC ++, the "Access Violation" error is prompted during DEBUG ". 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 for comparing the BOOL, int, float, pointer variable and "zero value" respectively (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 0 value of the BOOL variable, 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 to use if (var = NULL), which is a good programming habit.

Float variables are not accurate, so do not use "=" or "! = "To the number, you should try to convert it into the form of"> = "or" <=. If it is written as if (x = 0.0), an error is returned. 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:

When the array name in the Func (char str [100]) function acts as a function parameter, In the function body, the array name loses its meaning and is just a pointer; while losing its meaning, it also loses its constant feature. It 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 usage) is 4 bytes, so sizeof (str) and 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, "Parameters" were replaced 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) the effect on MIN (* p ++, B) is as follows:

(* 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 solution adds ";" behind the macro definition, showing that the author's macro concept is vague and can only be ruthlessly scored 0 points and eliminated by the interviewer.

Question 4: Why do standard header files have a structure similar to the following?

# Ifndef _ INCvxWorksh
# Define _ INCvxWorksh
# Ifdef _ cplusplus

Extern "C "{
# Endif

Answer:

Compile macro In header file

# Ifndef _ INCvxWorksh
# Define _ INCvxWorksh
# Endif

To prevent repeated references.

As an object-oriented language, C ++ supports function overloading, while Procedural Language C does not. After the function is compiled by C ++, the name in the symbol library is different from that in the C language. For example, assume that the prototype of a function is:

Void foo (int x, int y );

After the function is compiled by the C compiler, the name in the symbol library is _ foo, while the C ++ compiler generates names such as _ foo_int_int. The names such as _ foo_int_int contain the function name and the number and type of function parameters. C ++ uses this mechanism to implement function overloading.

In order to realize the mixed programming of C and C ++, C ++ provides the C connection to exchange the specified symbol extern "C" to solve the name matching problem, after the extern "C" is added before the function declaration, the compiler will compile the function as _ foo in the C language, so that the C ++ function can be called in the C language.

++ ++

Question 5: Write a function to shift n loops of a char string to the right. For example, if "abcdefghi" is n = 2, it should be "hiabcdefgh" after the shift"

The function header is as follows:

// PStr is a pointer to a string ending with '0'
// Steps is the n that requires moving

Void LoopMove (char * pStr, int steps)
{
// Fill in...
}

Answer:

Answer 1:

Void LoopMove (char * pStr, int steps)
{
Int n = strlen (pStr)-steps;
Char tmp [MAX_LEN];
Strcpy (tmp, pStr + n );
Strcpy (tmp + steps, pStr );
* (Tmp + strlen (pStr) = '0 ';
Strcpy (pStr, tmp );
}

Correct answer 2:

Void LoopMove (char * pStr, int steps)
{
Int n = strlen (pStr)-steps;
Char tmp [MAX_LEN];
Memcpy (tmp, pStr + n, steps );
Memcpy (pStr + steps, pStr, n );
Memcpy (pStr, tmp, steps );
}

Analysis:

This question mainly examines the interviewer's proficiency in the standard library functions. When necessary, referencing the library functions can greatly simplify the workload of programming.

The most frequently used library functions include:

(1) strcpy

(2) memcpy

(3) memset

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.