C ++ general questions

Source: Internet
Author: User

(1) Write a function to copy the memory

Void * memcpy (void * DST, const void * SRC, unsigned int Len)
{
Register char * D;
Register char * s;
If (LEN = 0)
Return DST;
If (DST> SRC) // consider Overwriting
{
D = (char *) DST + len-1;
S = (char *) SRC + len-1;
While (LEN> = 4) // expand the loop to improve execution efficiency
{
* D -- = * s --;
* D -- = * s --;
* D -- = * s --;
* D -- = * s --;
Len-= 4;
}
While (Len --)
{
* D -- = * s --;
}
}
Else if (DST <SRC)
{
D = (char *) DST;
S = (char *) SRC;
While (LEN> = 4)
{
* D ++ = * s ++;
* D ++ = * s ++;
* D ++ = * s ++;
* D ++ = * s ++;
Len-= 4;
}
While (Len --)
{
* D ++ = * s ++;
}
}
Return DST;
}

(2) Use of static keywords


The static keyword is a keyword that exists in both C and C ++. It mainly has three usage methods, the first two of which are used in C/C ++, the third method is only used in C ++.


General answer:
1. restrict the scope of the variable; 2. Set the storage domain of the variable to be visible only in the variable-specific source file.

 

<1> Local
Static variables

In C/C ++, local variables can be divided into three types: auto, static, and register.

Compared with the auto-type (common) local variable, the static local variable has three differences.
1. Different Storage space allocations
Auto type is allocated inStack


Is a dynamic storage class, occupies the dynamic storage space, and is automatically released after the function call ends, while static is allocated inStatic storage Zone

, Will not be released during the entire running of the program. The scope of the two is the same, but the lifetime is different.
2. Static local variables are stored in the moduleFirst Run

ProceedInitialization

Work only once
3. For local static variables, if no initial value is assignedAuto-assigned Initial Value 0 or null characters

While the initial values of the auto type are uncertain. (except for class objects in C ++, if the class object instance is not initialized, the default constructor is automatically called, regardless of whether the class is static or not)

Features: "Memory" of static local variables and "Global" of lifetime"
The so-called"Memory
"Indicates that the value of the first function call exit can be maintained when the second function call is started, that is, the results of each operation are different, which will damage the repeatability of the program running;

"Lifetime
"Global and uniqueness. the storage space of common local variables is allocated to the stack. Therefore, the allocated space may be different each time a function is called. Static has the global uniqueness feature, all point to the same memory, which leads to a very important problem-re-import is not allowed !!!
In this wayMulti-Thread Programming


OrRecursive programming



Pay special attention to this issue.

<2> external
Static variables/functions

Used to indicate that the object cannot be accessed by other filesGlobal Variables
AndFunction
. However, to restrict the scope of global variables/functions, add static before a function or variable to make the function a static function. However, the meaning of "static" here is not the storage method, but the scope of the function is onlyLimited to this document
(So it is also called an internal function ). Note that, whether static or not, external (global) variables are stored in the static storage area and the lifetime is global. at this time, static only applies to the scope, and the scope is limited within this module (file.
The advantage of using internal functions is that when different people write different functions, you don't have to worry about your own defined functions and whether they will have the same name as the functions in other files.

Summary:

1. Within a module (but in the external body of the function), a variable declared as static can be accessed by the function used in the module, but not by other functions outside the module. It is a local global variable.
2. In a module, a function declared as static can only be called by other functions in the module. That is, this function is restricted to use within the local scope of the module that declares it.

<3> static data member/member functions

C ++ gives this keyword a third meaning different from the previous one: RepresentationBelongs to a class

WhileDoes not belong to any specific object of this class

Variable and function. this is the biggest difference between a function and a common member function and its application. For example, when counting an object of a class, counting the number of instances of the class is generated, you can use static data members. static does not limit the scope or extend the lifetime, but indicatesUniqueness of variables/functions in this class

. This is also the meaning of "variables and functions that belong to a class rather than any specific objects of this class. because it is unique for the entire class, it cannot belong to an instance object. (For static data members, whether the member function is static or not, there is only one copy in the memory. When calling a common member function, this pointer must be passed in. When calling a static member function, no this pointer .)


 

 

What are global variables and local variables in the memory?
Global variables are stored in the Global static storage area, and local variables are stored in the stack.
 

 


 

 

(3) What are the differences between references and pointers?


1) The reference must be initialized and the pointer is not required.
2) The reference cannot be changed after initialization. the pointer can change the object.
3) There is no reference pointing to a null value, but there is a pointer pointing to a null value.

(4) write the if statement for comparing float X with "zero value"

----------------------------------------------------

Const float epsinon = 0.00001;
If (x> =-epsinon) & (x <= epsinon)

----------------------------------------------------

The storage mechanism of floating point numbers in memory is different from that of integer types.Rounding Error
,

An Approximate Representation of any real number in a computer. Specifically, this real number is obtained by multiplying an integer or a fixed number (that is, the ending number) by the integer power of a certain base number (usually 2 in the computer, this representation is similar to the scientific notation with a base of 10.
Therefore, floating point numbers are usually accompanied by approximation or rounding because they cannot be accurately expressed. But the benefit of this design is that it can store a larger range of numbers on a fixed length.
For example, a four-digit floating point number with an exponential range of ± 4 can be used to represent 43210, 4.321, or 0.0004321, but there is not enough accuracy to represent 432.123 and 43212.3 (must be approximately 432.1 and 43210 ). Of course, the actual number of digits is generally larger than 4.
So floating point numbers cannot be equal
,

If (x = 0) is not always correct. We recommend that youThe range is used to determine. If X is within a certain range, we think it is equal.


As for how to define the range, it depends on the actual situation. Float and double are different.
So const float epsinon = 0.00001;
If (x> =-epsinon) & (x <= epsinon) is advisable
As for why 0.00001 is used, you can define it as needed.

-----------------------------------------------------------------------

| The above solution may be something earlier than 8086. We can use a command to compare the compilation. If we want to test the accuracy, we can change it to something other than 0, for example, 0.00002,

| Then: If (x-0.00002> 0.000001 & x-0.0002 <-0.000001)
-----------------------------------------------------------------------

 

 

(5) 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);

 

 

A macro definition can implement functions similar to a function, but it is not a function, and the "parameter" in an arc in a 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, the strict answer is as follows:

        

# Define min (A, B) (a) <= (B )? (A): (B)
// Note that there is no Semicolon ";"





 

(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 ++ ))


Obviously, this expression produces side effects. The pointer P performs three ++ auto-increment operations.

(6) extern "C"

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, false
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 extern "C" is added before function declaration:


Extern "C"
Void Foo (int x, int y );



 

Then the compiler willC Language
Compile the function as _ Foo.C language can call C ++ Functions
.

The true purpose of extern "C" is to implementMixed Programming of class C and C ++
. Add extern "C" before the statement in the C ++ source file, indicating that it is compiled and connected according to the C compilation and connection protocol, rather than the connection protocol of C ++ compilation. In this way, the C ++ function or variable can be called in the code of class C. (Note: The Class c I mentioned here represents all languages consistent with the C language compilation and Connection Methods)

See http://www.cnblogs.com/skynet/archive/2010/07/10/1774964.html
(Good)

Http://www.cppblog.com/Macaulish/archive/2008/06/17/53689.html

(7) memset (), memcpy (), memccpy (), memmove (), bcopy (), strcpy (), strncpy ()

 

Void * memset (void * s, int C, int strlen );
Void * memcpy (char * str_d, char * str_s, int N );
Void * memccpy (void * DEST, const void * SRC, int C, int N );
Void * memmove (void * DEST, const void * SRC, int N );
Void bcopy (const void * SRC, void * DEST, int N );
Char * strcpy (char * DEST, const char * SRC );
Char * strncpy (char * DEST, const char * SRC, int strlen );

The above functions are frequently encountered in C programming. Below is a simple explanation of each function:
Void * memset (void * s, int C, int N)

Fill in the first n Bytes of the memory area pointed by the pointer s with the integer value c. Return the pointer s pointing to the memory area. S is not necessarily a pointer to a character. It can be a pointer to any type, or even a pointer to a structure.

Void * memcpy (void * DEST, const void * SRC, int N)

Copy the first n Bytes pointed to by the SRC pointer to the first n memory regions pointed to by the DeST. If SRC and DEST have repeated regions, the data will be overwritten. That is, the data will be moved back during the copy process. This will not achieve the expected results, and memmove will be used at this time.
.

--------------------------------------------------------------

Memcpy: Copies non-overlapping memory blocks.
Void * memcpy (void * pvto, void * pvfrom, size_t size) // byte is the variable type in Java
{
Assert (pvto! = NULL & pvfrom! = NULL );
Void * pbto = (byte *) pvto;
Void * pbfrom = (byte *) pvfrom;
/* Does the memory block overlap? If they overlap, use memmove */
Assert (pbto> = pbfrom + size | pbfrom> = pbto + size );
While (size --> 0)
* Pbto ++ = * pbfrom ++;
Return pvto;
}

 

In addition, memcpy () is used to copy the first n Bytes of memory content in SRC to the memory address in DeST.Unlike strcpy (), memcpy () completely copies n Bytes and does not end with a string ending '/0'.



--------------------------------------------------------------

Void * memmove (void * DEST, const void * SRC, int N)

The difference between this function and the preceding function is that when SRC and desc have repeated regions, DESC is first moved back before the copy operation.

Void * memccpy (void * DEST, const void * SRC, int C, int N );

The memccpy () function copies no more than n Bytes from memory area SRC to memory area DEST, stopping when the character C is found.
The returned result is a character pointing to the first C character in DeST. If C is not found in the first n characters of SRC, null is returned.

Void bcopy (const void * SRC, void * DEST, int N );

Copy n Bytes from SRC to DeST. If n = 0, copy 0 bytes

 

All the above copies areFor any data type

So the pointer type is void, and the strcpy and strncpy below are allString

.

 

Char * strcpy (char * DEST, const char * SRC );

Copy the string pointed to by the SRC pointer to the array pointed to by the dest, including. It cannot handle the issue of repeated regions, but the space pointed to by the Dest must be larger than that pointed to by the SRC.

Char * strncpy (char * DEST, const char * SRC, int N)

Copy the first n characters of the string pointed to by Src to the array pointed to by dest. If no ending character exists in the first n characters of SRC, neither does DeST. this is not the correct method.

The returned value is a pointer to a string. If the length of DeST is insufficient, an overflow error occurs.

 

--------------------------------------

The following is a simple implementation of several functions.

--------------------------------------

 

 // Strcpy (), string copy. <br/> char * strcpy (char * strdest, const char * strsrc) <br/>{< br/> assert (strdest! = NULL) & (strsrc! = NULL); <br/> char * address = strdest; <br/> while (* strdest ++ = * strsrc ++ )! = '/0') <br/> return address; <br/>}< br/> // memcpy, copy non-overlapping memory blocks <br/> void * memcpy (void * pvto, void * pvfrom, size_t size) // byte is the variable type in Java <br/>{< br/> assert (pvto! = NULL & pvfrom! = NULL); <br/> void * pbto = (byte *) pvto; <br/> void * pbfrom = (byte *) pvfrom; <br/>/* does the memory block overlap? If they overlap, use memmove */<br/> assert (pbto> = pbfrom + size | pbfrom> = pbto + size ); <br/> while (size --> 0) <br/> * pbto ++ = * pbfrom ++; <br/> return pvto; <br/>}< br/> void * memcopy (void * DEST, const void * SRC, size_t count) <br/>{< br/> char * pdest = static_cast <char *> (DEST ); <br/> const char * psrc = static_cast <const char *> (SRC); <br/> If (pdest> psrc & pdest <psrc + count) <br/> {<br/> for (size_t I = count-1; I <= 0; ++ I) <Br/>{< br/> pdest [I] = psrc [I]; <br/>}< br/> else <br/> {<br/> for (size_t I = 0; I <count; ++ I) <br/>{< br/> pdest [I] = psrc [I]; <br/>}< br/> return pdest; <br/>}< br/> void * memmove (void * DST, const void * SRC, size_t count) <br/>{< br/> assert (DST & SRC); <br/> void * pdst = DST; <br/> If (DST <SRC & (char *) DST> (char *) SRC + count) <br/>{< br/> while (count --) <br/> {<br/> * (char *) DST = * (char *) SRC; <br/> DST = (char *) DST + 1; <br/> src = (char *) SRC + 1; <br/>}< br/> else <br/> {<br/> DST = (char *) DST + count-1; <br/> src = (char *) SRC + count-1; <br/> while (count --) <br/>{< br/> * (char *) DST = * (char *) SRC; <br/> DST = (char *) DST-1; <br/> src = (char *) Src-1; <br/>}< br/> return pdst; <br/>}</P> <p> void * memmove (void * DEST, const void * SRC, size_t N) <br/>{< br/> If (n = 0) retu Rn 0; <br/> If (DEST = NULL) return 0; <br/> If (src = NULL) return 0; <br/> char * psrc = (char *) SRC; <br/> char * pdest = (char *) DEST; <br/> If (DEST <= psrc) | (pdest> = psrc + n)/* Check for overlap issues */<br/> {<br/> for (INT I = 0; I <N; I ++)/* Forward copy */<br/>{< br/> * pdest = * psrc; <br/> psrc ++; <br/> pdest ++; <br/>}< br/> else/* reverse copy */<br/> {<br/> psrc + = N; <br/> pdest + = N; <br/> for (INT I = 0; I <n; I ++) <br/> {<Br/> psrc --; <br/> pdest --; <br/> * pdest = * psrc; <br/>}< br/> return DEST; <br/>}< br/> // memset: set the first count bytes of the memory area referred to by buffer to the character C <br/> void * memset (void * buffer, int C, int count) <br/>{< br/> char * pvto = (char *) buffer; <br/> assert (buffer! = NULL); <br/> while (count --> 0) <br/> * pvto ++ = (char) C; <br/> return buffer; <br/>}

 

(8) differences between pointers and references

1. From a symptom perspective: A pointer can change the value it points to at runtime, and the reference will not change once it is bound to an object.
2. From the memory allocation Perspective: The program allocates a memory area for the pointer variable, but the reference does not allocate a memory area.
3.
In terms of compilation, the program adds pointers and references to the symbol table during compilation. the symbol table records the variable name and the address corresponding to the variable. The address value corresponding to the pointer variable in the symbol table is the address of the pointer variable.
And the address value corresponding to the referenced symbol table is the address value of the referenced object. The symbol table will not be changed after it is generated, so the pointer can change the object to which it points (the value in the pointer variable can be changed), but the referenced object cannot
Change.


★Similarities:
1. All are addresses;
The Pointer Points to a piece of memory, whose content refers to the address of the memory, and the reference is the alias of a piece of memory.

★Differences:
1. the pointer is an entity, and the reference is only an alias;
2. You do not need to unreference (*) when using a reference. The pointer must be unreferenced;
3. The reference can only be initialized once during definition, and will not be changed afterwards; the pointer will be variable;
Reference "from one end" ^_^
4. The reference has no const, the pointer has const, And the pointer of const is immutable;
5. The reference cannot be blank, and the pointer can be blank;
6. "sizeof reference" gets the size of the variable (object) to which it points, while "sizeof Pointer" gets the size of the pointer itself (the address of the variable or object to which it points;
Typeid (t) = typeid (T &) always true, sizeof (t) = sizeof (T &) always true,
However, when a reference is a member, the occupied space is the same as that of the pointer (the standard rule is not found ).
7. the pointer and reference auto-increment (++) operations have different meanings;

 

★Contact
1. Reference is implemented using pointers within the language.
2. For general applications, the reference is understood as a pointer and no serious semantic error is made. A reference is a pointer with limited operations (only content operations are allowed ).

 

 

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.