Classic interview questions often encountered in C/C++ interviews

Insert picture description here
If you want to go to the C++ interview, check it out. I searched on the Internet, I just saw it, so I will sort it out.

1. What is the difference between variable declaration and definition?

Constant: the amount that will not change during the execution of the program, and the amount that cannot be changed.
Variable: the amount that can be changed during the execution of the program. How to
define variables: data type variable name = constant;
int num = 10; //Define (allocate storage space, initial value is constant)
int num;//defining declaration (allocate storage space, allocate garbage value)
extern int num;//referential declaration referncing declaration, (do not allocate storage space, Do not assign garbage value) is not limited to the use of this document.
• The definition of a variable is used to allocate storage space for the variable, and you can also specify an initial value for the variable. In a program, a variable has one and only one definition
. Under normal circumstances, we often describe it like this. The declaration that establishes space is called "definition", and the declaration that does not need to establish storage space is called "declaration". Obviously, the declaration we are referring to here is a narrower declaration, that is, a declaration in a narrow sense, that is, a non-definition statement
. When a function is declared, the compiler does not assign an entry address to the
function. When a function is defined, the function code segment will Is placed in the code block, even if storage space is allocated to the function at this time, the function name maps the entry address of the function.
• The ultimate purpose of the declaration is to use it in advance, that is, to use it before the definition. If you do not need to use it in advance, there is no need to declare separately. This is the case for variables and functions. Therefore, the declaration does not allocate storage space, and only allocates when it is defined storage

2. Write an if statement that compares a bool int float pointer variable with a zero value

Bool type data
If (flag)
If (!flag)

Int data:
if(0!=flag)
If(0==flag)

Pointer data:
if(NULL==flag)
If(NUJLL!=flag)

Float 型数据:
Define NORM 0.00001;
if(flag>=-NORM && flag<=NORM)

Note: Pay special attention to when comparing int, pointer variable and zero value, put the zero value on the left, so that when the == is incorrectly written as =, the compiler can report an error, otherwise the logic error is not easy to find and may Lead to very serious consequences.

3. The difference between sizeof and strlen

The difference between sizeof and strlen is as follows:
sizeof is an operator, strlen is
the parameter of the library function sizeof, which can be the type of data or a variable, and strlen can only be a string ending with'\0' as a parameter.
Compiler compiles and calculates the result of sizeof, and the strlen function must be run to calculate it. And sizeof calculates the size of the memory occupied by the data type, while strlen calculates the actual length of the string. The
array does not degenerate as the parameter of sizeof, and passing strlen degenerates into a pointer.
Note: Some operators look like functions, and some function names look like operators. Such confusing names must be distinguished, otherwise it is easy to make mistakes when encountering special data types such as array names as parameters . The operator most easily confused as a function is sizeof.

4. What is the difference between the keyword static of C language and the keyword static of C++

In C, static is used to modify local static variables and external static variables and functions. In addition to the above functions, C++ is also used to define the member variables and functions of the class, that is, static member variables and static member functions.
Note: The static memory and global characteristics of programming can allow functions to be called in different periods to perform Communication, transfer information, and C++ static members can communicate between multiple object instances to transfer information.

5. What is the difference between malloc in c and new in c++

Malloc and new have the following differences:
new and delete are operators and can be overloaded.
Malloc can only be used in C++ . Free is a function that can be overwritten.
New can be used in both C and C++ to call the object's constructor. Corresponding delete calls the corresponding destructor
Malloc only allocates memory, free only reclaims memory, and does not execute the constructor and destructor.
New delete returns a pointer of a certain data type, malloc free returns a void pointer.
Note: the memory requested by malloc The space should be released with free, and the memory space requested by new should be released with delete. Don't confuse it, because the two implementation mechanisms are different

6. Write a standard macro MIN

#define min(a,b)((a)<=(b)?(a):(b))
Note: Be sure to pay attention to the side effects of this macro definition when calling, call as follows
(++*p)<( x)?(++*p):(x) The
P pointer has been added twice, which violates the original intention of MIN.

7. Can a pointer be made volatile

Volatile is used in the following places:
1. Variables modified in the interrupt service program for detection by other programs need to add volatile;
2. The flags shared between tasks in a multitasking environment should add volatile;
3. Memory-mapped hardware registers The volatile description is usually added, because each reading and writing to it may have a different meaning;
Insert picture description here

8. What is the difference between a and &a

Please write the print result of the following code, the main purpose is to examine the difference between a and &a
#include<stdlo.h>
Void main()
{ Int a[5]={1,2,3,4,5}; Int * ptr=(int )(&a+1); Printf(“%d,%d”,(a+1), (ptr-1)); Return; }




Output result: 2,5
Note: The array name a can be used as the first address of the array, and &a is a pointer to the array.
Think about it,
what will be the output when the original int* ptr=(int *)(&a+1); should be int *ptr=(int *)(a+1)

9 Briefly describe the memory allocation of C and C++ program compilation

(1) Allocation from static storage area: The
memory is allocated when the program is compiled. This memory exists during the entire running period of the program. It is fast and error-free, because the system will clean up, for example, global variables, static variables etc.
(2) allocated on the stack:
when executing the function, the function of the local variable storage unit are created on the stack, the function of these memory cells are automatically released at the end of the execution stack memory allocation operation to focus on instruction processor built , High efficiency, but the allocated memory capacity is limited.
(3) Allocating from the heap:
dynamic memory allocation, the program uses malloc or new to apply for any size of memory when the program is running, and the programmer is responsible for when to release the memory with free or delete. The lifetime of dynamic memory is determined by the programmer, and it is very flexible to use. If space is allocated on the heap, it is the responsibility to reclaim it, otherwise the running program will have memory leaks. In addition, frequent allocation and release of different sizes of heap space will Generate debris in the heap.
When a C, C++ program is compiled, the memory is divided into five storage areas: heap area, stack area, global area, text constant area, and program code area

10 Briefly describe the difference between strcpy, sprintf and memecpy

The three main differences are as follows
(1) The operation objects are different: the two operation objects of strcpy are strings, the operation objects of sprintf can be multiple data types, and the target operation object is a string, and the two objects of memcpy are Two arbitrary operable memory addresses are not limited to any data type.
(2) Different execution functions: strcpy mainly realizes the copy between string variables, sprintf mainly realizes the conversion of other data type formats to string types, memcpy is mainly the copy between memory blocks
(3) Different execution efficiency: memcpy is the highest, sprintf Minimum
Description: strcpy, sprintf, memcpy can all realize the copy function, but the target is different, according to the actual needs, choose the appropriate function to realize the copy function

11. Set the value of the integer variable whose address is ox67a9 to oxaa66

int *ptr;
Ptr=(int *)ox67a9;
*Ptr=oxaa66;
Note: This question is a typical example of forced type conversion, no matter what platform the length of the address and the length of the integer data are the same, that is, an integer Data can be coerced into an address pointer type, as long as it makes sense.

12. Three characteristics of object-oriented

The three characteristics of object-oriented are encapsulation, inheritance, and polymorphism.

13. What are the member functions of the C++ empty class

(1) Default constructor
(2) Default copy constructor
(3) Default destructor
(4) Default assignment operator
(5) Default address operator
(6) Default access Address operator const
Note: Some books simply introduce the first four functions without mentioning the latter two functions, but the latter two functions are also the default functions of the empty class. In addition, Western medicine pays attention to that, only when these functions are actually used, the compiler will define them.

14. Talk about your knowledge of copy constructors and assignment operators

Copy constructor and copy operator overloading have the following two differences:
(1) The copy constructor generates a new class object, and the assignment operation cannot
(2) Since the copy constructor directly constructs a new class object, it is initialized This object does not need to check whether the source object is the same as the newly created object, and the assignment operator requires this operation. In addition, if the memory in the original object is not allocated in the assignment operator, the memory must be released first.
Note: When the class has a pointer type When making member variables, be sure to rewrite the copy constructor and assignment operator instead of using the default ones.

15. Briefly describe the difference between rewriting, overloading and hiding of class member functions

(1) and heavy rewriting mainly for the following points:
range difference: to be rewritten and rewriting function in two classes, the overloaded overloading and functions in the same class
distinction Parameters : The parameter list of the rewritten function and the rewritten function must be the same, and the parameter list of the overloaded function and the overloaded function must be different.
Virtual difference: the rewritten function in the rewritten base class must have virtual Decoration, and overloaded functions and overloaded functions can be virtual decorated or not.
(2) Hidden and overridden. Overloading has the following differences:
the scope of overloading is different. Like overriding, hidden function and hidden function are not in the same class.
The difference between parameters: hidden function and hidden function The parameter list can be the same or different, but the function name must be the same. When the parameters are not the same, regardless of whether the parameters in the base class are modified by virtual, the functions of the base class are hidden instead of being overridden.
Note: Although both overloading and coverage are the basis for achieving polymorphism, the technologies implemented by the two are completely different, and the goals achieved are completely different. Coverage is a dynamically bound polymorphism, while overloading is a static binding. state

16. Briefly describe the principle of polymorphism

When the compiler finds a virtual function in a class, it will immediately generate a virtual function table vtable for this class. The entries in the virtual function table are pointers to the corresponding virtual function. The compiler will also implicitly insert a pointer into this class. vptr (for the vc compiler, it is inserted in the first position in the class) points to the virtual function table. When the constructor of this class is called, the compiler will implicitly execute the associated code of vptr and vtable, and point vptr to The corresponding vtable connects the class with the vtable of this class. In addition, when the constructor of the class is called, the pointer to the base class has now become the this pointer to the specific class, so relying on this this pointer can get the correct The vtable can really be connected with the function body in this way. This is the basic principle of dynamic binding and polymorphism.
Note: We must distinguish between virtual functions, pure virtual functions, and virtual inheritance. Keep in mind the principle of virtual function realization, because one of the important test points of polymorphic C++ interview, and virtual function is the basis for polymorphism.

17. What is the difference between linked list and array

Array and linked list are different in the following points:
(1) Storage form: array is a continuous space, the length must be determined when declaring, the linked list is a discontinuous dynamic space with variable length, and each node must save adjacent Pointer to the node.
(2) Data search: The linear search speed of the array is fast. The search operation directly uses the offset address. The linked list needs to retrieve the nodes in order, which is inefficient.
(3) Data insertion and deletion: the linked list can quickly insert and delete nodes, while the array It may require a large amount of data movement.
(4) Out-of-bounds problem: Linked list does not have out-of-bounds issue. Array has out-of-bounds issue.
Description: When selecting array or linked list data structure, you must choose according to actual needs. Array is easy to query, and linked list is easy to insert and delete. Array saves space but length Fixed, although the linked list becomes longer, it takes up more storage space

18. How to reverse a singly linked list

1. Reverse cyclic algorithm of singly linked list

  1. There are two types of linked lists:
    • Leading node: The head node stores length information, and the next of the head node points to the first actual node;
    • Without the head node, the head node is the first node;
    • The head node is used here. Linked list of nodes;
  2. Three pointers are needed to record the current node (for reversal), the previous node, and the next node (for forwarding after reversing).
    The code is as follows:
    /*
    linked list
    1. Leading node: the length of the linked list (or other information) is stored in the head, head->next points to the first actual node;
    2. Without the leading node: head is the first actual node
    */
    typedef struct Node
    { int data; Node * next; }; void reverseList(Node *head) { if ((head==NULL)||((head->next)==NULL)) return; //if If head is empty, or the head node points to an empty node (the length of the linked list is 0), then exit. Node *pre,*cur,*next; //cur records the current position, pre records the previous position, which is the value of cur->next; next records the next position, cur is not equal to cur->next cur=head after inversion ->next; pre=NULL; //After the reversal, the head node becomes the tail node, and its next is Null while (cur!=NULL) { next=cur->next; //You can no longer use cur- after reversing >next, so first record this node cur->next=pre; pre=cur; cur=next;















    }
    head->next=pre; //cur is already empty, so pre is the tail node. head->next points to it.
    return;
    }

2. Recursive algorithm for reversing singly linked list The
code is as follows:
List *reverse( List *oldList, List *newHead = NULL)
{ List *next = oldList-> next; //Record the linked list after the last flip oldList-> next = newHead; //Insert the current node at the beginning of the linked list after flipping newHead = oldList; //Recursively process the remaining linked list return (next==NULL )? newHead: reverse( t, newHead ); }




19. Briefly describe the similarities and differences between queues and stacks

Queue and stack are both linear storage structures, but the operations of inserting and deleting data are different. The queue is first-in first-out, and the stack is last-in first-out.
Note: The stack area and the heap area are distinguished from each other. The access order of the heap area is arbitrary. The stack area is last-in, first-out. The stack is automatically allocated by the compiler to store function parameter values, local variable values, etc. Its operation is similar to the stack in the data structure. The heap is generally allocated and released by the programmer, if the programmer does not release , When the program ends, it may be recycled by os. The allocation method is similar to the linked list. It is different from the heap and stack of this question. The stack is just a data structure, and the heap area and the stack area are different memory storage areas in the program.

Finally, I wish the interviewees success.
Insert picture description here

There may be deficiencies above, welcome to point out the discussion, friends who feel good hope to get your forwarding support, and can continue to follow me.
(Follow + private message: C++, get learning materials and videos)
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_52622200/article/details/110281341