A summary of the written and interview topics in C + + 2

Source: Internet
Author: User
Tags variable scope

Http://www.cnblogs.com/fangyukuan/archive/2010/09/18/1830493.html

I. Finding the wrong question

Question 1:

void Test1 ()
{
CHARSTRING[10];
char* str1 = "0123456789";
strcpy (string, str1);
}

Question 2:

void Test2 ()
{
CHARSTRING[10],STR1[10];
int i;
for (i=0; i<10; i++)
{
str1 = ' a ';
}
strcpy (string, str1);
}

Question 3:

void Test3 (char* str1)
{
CHARSTRING[10];
if (strlen (str1) <=10)
{
strcpy (string, str1);
}
}

Answer:
Question 1 The string str1 requires 11 bytes to be stored (including the end of ' + '), while the string has only 10 bytes of space, and strcpy causes the array to be out of bounds;

For question 2, if the interviewer points out that the character array str1 cannot end within the array, it can give 3 points, and if the interviewer indicates that strcpy (STRING,STR1) call makes the number of bytes copied from str1 memory copied to string memory, there is uncertainty that can give 7 points, Based on the above, the paper points out that the library function strcpy 10 points to the working mode;

The question 3,if (strlen (str1) <= 10) should be changed to if (Strlen (STR1) < 10) Because the result of Strlen does not count the 1 bytes occupied by '% '.

Analysis:
To examine the mastery of basic skills:
(1) The string ends with ' n ';
(2) The sensitivity of the cross-border of the logarithm group;
(3) Library function strcpy, if you write a standard strcpy function, the total score value is 10, the following gives a few different points of the answer:

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 (&AMP;STR, 100);
strcpy (str, "Hello");
printf (str);
}

Question 7:

void Test (void)
{
Char*str = (char*) malloc (100);
strcpy (str, "Hello");
Free (str);
...//omitted other statements
}

Answer:
Question 4 The formal parameter passed in to the GetMemory (char *p) function is a string pointer, and modifying the parameter inside the function does not really change the value of the passed-in parameter, after executing

char *str = NULL;
GetMemory (str);
After the STR is still null;

in question 5
Char p[] = "Hello World";
return p;
P[] Array is a local automatic variable within a function, and after the function returns, the memory is freed. This is a common mistake many programmers make, the root of which is the failure to understand the lifetime of a variable.

The getmemory of question 6 avoids the problem of question 4, the parameter passed in GetMemory is a pointer to a string pointer, but executes the request memory and assignment statement in GetMemory

*p = (char *) malloc (num);
After not judging whether the memory is successful, you should add:

if (*p = = NULL)
{
...//To request memory failure handling
}

Question 7 has the same problem as Test 6, in the execution
Char *str = (char *) malloc (100);
If the memory is not applied to determine the success of the application, in addition, the blank str after free (str), which may become a "wild" pointer, should be added:

str = NULL;

The memory of malloc has not been freed from Test 6 's function.

Analysis:
The Test 4~7 examines the interviewer's understanding of the memory operation, and the basic skills of the interviewer are generally able to correctly answer the 50~60 errors. But it's not easy to answer it all right.

The memory operation is mainly focused on:
1) understanding of pointers;

2) The lifetime and scope of the variables;
3) Good dynamic memory application and release habits.

Let's see what's wrong with the following program:

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 area, causing the program to run in a crash. In VC + + Debug Runtime prompt error "Accessviolation". The procedure should read:

Swap (int* p1,int* p2)
{
int p;
P =*P1;
*P1 =*P2;
*P2 = p;
}

Two. Internal problems

Question 1: Given the bool,int,float, the IF statement of the pointer variable compared to the "0 value" (assuming that the variable is named Var)

Answer:

BOOL type variable: if (!var)

Type int variable: if (var==0)

Float type variable:

const float Epsinon = 0.00001;

if ((x >=-Epsinon) && (x <=epsinon)

Pointer variable: if (var==null)

Analysis:

To examine the "internal strength" of the 0 value judgement, the BOOL type variable 0 judgment can be written as if (var==0), and the int variable can also be written as if (!var), pointer variable judgment can also be written as if (!var), the above notation, although the program can be correctly run, But failed to express the meaning of the program clearly.
In general, if you want the if to determine the "true", "false" of a variable, you should use if (Var), if (!var), to indicate that it is "logical" judgment, if you use if to determine a numeric variable (short, int, long, etc.), should be used if (var==0), It is a good programming habit to use the IF (var==null) to judge the pointer when it is compared with 0 for "numerical value".

Floating-point variables are not accurate, so float variables cannot be "= =" or "! = "In comparison with numbers, you should try to convert them into" >= "or" <= "forms. If written as if (x = = 0.0), then the sentence is wrong, 0 points.

Question 2: The following is a 32-bit C + + program under WindowsNT, please calculate the value of sizeof

void Func (char str[100])
{
sizeof (str) =?
}
Void*p = malloc (100);
sizeof (p) =?

Answer:

sizeof (str) = 4
sizeof (P) = 4
Analysis:

Func (char str[100]) function in the array name as a function parameter, in the function body, the array name loses its own connotation, just a pointer, in the loss of its connotation at the same time, it also lost its constant characteristics, can be self-increment, self-reduction and other operations, can be modified.

The nature of the array name is as follows:
(1) Array name refers to a data structure, this data structure is an array;

For example:

Char str[10];
cout << sizeof (str) << Endl;

The output result is 10,STR data structure char[10].

(2) The array name can be converted to a pointer to its reference entity, and is a pointer constant, can not be self-increment, self-reduction and other operations, can not be modified;

Char str[10];
str++; Compilation error, indicating that STR is not an lvalue

(3) When the array name is a function parameter, it is reduced to a normal pointer.

Under the Windows NT 32-bit platform, the length of the pointer (memory size) is 4 bytes, so sizeof (str) and sizeof (p) are 4.

Questions 3 : Write a " Standard " Macro MIN , this macro enters two parameters and returns the smaller one. Also, what happens when you write the following code?

least = MIN (*p++, b);

Answer:
#define MIN (A) (A) <= (B)? (A): (B))
MIN (*p++, B) can produce macro side effects

Analysis:
This question mainly examines the interviewer's use of the macro definition, which can implement functions similar to a function, but it is not a function at all, but the "parameters" in the brackets in the macro definition are not real arguments, and the "parameters" are replaced one-to-a-time when the macro is expanded.

Programmers should be very careful with the use of macro definitions, paying special attention to two questions:

(1) Carefully enclose the "parameters" in the macro definition and the entire macro in parentheses. So, strictly speaking, the following answers:

#define MIN (A) (A) <= (b)? (A): (B)
#define MIN (A <= B) A:B) should be sentenced to 0 points;

(2) Prevent the side effects of the macro.

Macro definition # define MIN (A) (A) <= (B)? (A): (b) The effect of min (*p++, B) is as follows:

((*p++) <= (b)? (*p++): (*p++))

This expression can have side effects, and pointer p will do three + + self-increment operations.

In addition, another 0-point answer is:

#define MIN (A) (A) <= (B)? (A): (B));
This solution adds ";" to the macro definition, showing that the writer's concept of the macro is vague and can only be ruthlessly sentenced to 0 points and eliminated by the interviewer.

The function header is this:

PSTR is a pointer to a string ending with '/'
Steps is required to move n
void Loopmove (char* pStr, int steps)
{
Please fill in ...
}

Answer:

Correct 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)) = ' + ';
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 paper mainly examines the interviewer's proficiency in standard library functions, and when needed, referencing library functions can greatly simplify the work of programming.

The most frequently used library functions are:

(1) strcpy
(2) memcpy
(3) Memset

Question 6: The WAV file format is known as the following table, open a WAV file, organize the WAV file header with the appropriate data structure and parse the information in WAV format.

Wave File Format Description table

Offset address

Number of bytes

Data type

Content

File header

10)

4

Char

"RIFF" flag

04H

4

Int32

File length

08H

4

Char

"WAVE" logo

0CH

4

Char

"FMT" flag

10H

4

Transition bytes (variable)

14H

2

Int16

Format category

16H

2

Int16

Number of channels

08)

2

Int16

Sample rate (number of samples per second), indicating the playback speed of each channel

1CH

4

Int32

Waveform audio data transfer rate

20H

2

Int16

Number of data block adjustments (in bytes)

22H

2

Number of data bits per sample

24H

4

Char

The data marker

28H

4

Int32

Length of voice data

Answer:
Define the WAV file format as struct Waveformat:

typedef struct TAGWAVEFORMAT
{
Char criffflag[4];
UIN32 Nfilelen;
Char cwaveflag[4];
Char cfmtflag[4];
Char ctransition[4];
UIN16 Nformattag;
UIN16 nchannels;
UIN16 nsamplespersec;
UIN32 navgbytespersec;
UIN16 nblockalign;
UIN16 nbitnumpersample;
Char cdataflag[4];
UIN16 naudiolength;

} Waveformat;

Assuming that the content of the WAV file is read out and stored in a memory cell that starts at the pointer buffer, the code for parsing the file format is simple:

Waveformat Waveformat;
memcpy (&waveformat, buffer,sizeof (Waveformat));
By accessing the members of the Waveformat directly, you can obtain the format information for a particular WAV file.

Analysis:
Question 6 examines the ability of the interviewer to organize the data structure, the experienced program designer will organize the members of a whole group into a structure, using the pointer type conversion, can use memcpy, memset and other functions directly to the structure of the address, the overall operation of the structure. Through this question can see the interviewer's programming experience is rich.

Question 7: Write the constructor, destructor, and assignment function of the class string, the prototype of the known class string is:

Class String
{
Public
String (constchar*str = NULL); Common constructors
String (const string &other); Copy constructor
~ String (void); Destructors
String & operator = (const string &other); Assignment function
Private
Char*m_data; Used to save strings
};
Answer:
Common constructors
String::string (CONSTCHAR*STR)
{
if (str==null)
{
M_data =newchar[1]; Score points: Automatically apply for empty string to hold the end flag '
Add points: null judgment on M_data
*m_data = ' + ';
}
Else
{
int length = strlen (str);
M_data =newchar[length+1]; Better if you can add a NULL judgment
strcpy (m_data, str);
}
}
destructor for string
String::~string (void)
{
delete [] m_data; or deletem_data;
}
Copy constructor
string::string (const String &other)//Score point: input parameter is const type
{
int length = strlen (Other.m_data);
M_data =newchar[length+1]; Add points: null judgment on M_data
strcpy (M_data, other.m_data);
}
Assignment function
String & string::operator = (const String &other)//Score point: input parameter is const type
{
if (This==&other)//score point: Check self-assignment
Return*this;
delete [] m_data; Scoring points: Releasing the original memory resources
int length = strlen (Other.m_data);
M_data =newchar[length+1]; Add points: null judgment on M_data
strcpy (M_data, other.m_data);
Return*this; Score points: Returns a reference to this object
}

Analysis:
The interviewer, who can write the constructor, copy constructor, assignment function, and destructor of the string class correctly, has at least 60% of the basic skills of C + +!
The pointer class member variable m_data is included in this class, and it is important to reload the copy constructor, assignment function, and destructor when the class includes pointer class member variables, which is both a basic requirement for C + + programmers and a special emphasis in effective C + +.
Study this class carefully, pay special attention to annotate points and points of significance, so that more than 60% of C + + basic Skills!

Question 8: Please say the static and const keywords as much as possible

Answer:
The static keyword has at least the following n functions:
(1) The function body static variable scope is the function body, different from the auto variable, the memory of the variable is allocated only once, so its value at the next call will still maintain the last value;
(2) The static global variable within the module can be accessed by functions used within the module, but not by other functions outside the module;
(3) The static function within the module can only be called by other functions within the module, and the use of the function is limited to the module in which it is declared;
(4) A static member variable in a class is owned by the entire class and has only one copy of all objects of the class;
(5) The static member function in a class is owned by the entire class, which does not receive the this pointer, and therefore can only access static member variables of the class.

The CONST keyword has at least the following n functions:
(1) To prevent a variable from being changed, you can use the Const keyword. When defining the const variable, it is often necessary to initialize it, since there is no chance to change it again;
(2) For pointers, you can specify that the pointer itself is a const, or you can specify that the pointer refers to a const data, or both of which are specified as const;
(3) In a function declaration, the const can modify the formal parameter, indicating that it is an input parameter, the value cannot be changed inside the function;
(4) For a class member function, if it is specified as a const type, it indicates that it is a constant function and cannot modify the member variables of the class;
(5) For a member function of a class, sometimes it is necessary to specify that its return value is a const type so that its return value is not "left value". For example:
Const ClassA operator* (const classa& a1,const classa& A2);
The return result of the operator* must be a const object. If not, such a perverted code will not compile an error:

ClassA A, B, C;
(A * b) = C; Assigning values to the results of a*b
Operation (A * b) = C clearly does not conform to the intended purpose of the programmer, nor does it make any sense.

Analysis:
Are you surprised? The little static and the const actually have so many functions, how many can we answer? If you can only answer one or two, then you really have to retreat and cultivate well.

This question can examine the interviewer's mastery of programming knowledge is primary, intermediate or relatively deep, without a certain breadth and depth of knowledge, it is impossible to give a comprehensive answer to this question. Most people can only answer some of the features of the static and const keywords.

three . Technical Questions

Question 1: Write a function that returns the value of 1+2+3+...+n (assuming that the result does not exceed the range of the long integer variable)

Answer:

int Sum (int n)
{
Return ((long) 1+ N) * N/2; or return (1l + N) * N/2;
}

Analysis:
For this question, it can only be said that perhaps the simplest answer is the best answer. The following answer, or based on the following solutions to optimize, no matter how "toss", its efficiency can not be compared with direct return (1 L + N) * N/2!

int Sum (int n)
{
Long sum = 0;
for (int i=1; i<=n; i++)
{
sum + = i;
}
return sum;
}

So programmers need to be sensitive to the use of mathematics and other knowledge in programming.

A/C + + written test, interview topic summary 2

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.