C ++ learning

xiaoxiao2021-03-06  49

1. Get time How to calculate how the time running? What function is used to get the current time? 1. Use DiffTime, second

#include #include #include

Int main (void) {TIME_T FIRST, SECOND

First = TIME (NULL); / * Gets System Time * /

// Your program ...............

Second = Time (null); / * gets system time again * /

Printf ("THE DIFCERENCE IS: F SECONDS / N", DIFFTIME (Second, First)); getCH ();

Return 0;}

2. Use dword gettickcount (void) ctime winapi getcurrenttime () throw (); get more accurate time GetTickCOUNT

3. Get the time char * TIME1 = __date __; char * TIME2 = __Time__ and __time__ is the two macros.

Second, IO operator

COUT << "Hello World!" << flush << Endl; - - Force Output Cout << Endl; Cout << Ends; ----- Output A NULL Character Cout << SETFILL ('*'); ---- and SETW, use the specified character output of the blank area to output COUT << SETW (14) << "How" << (14) << "How" << Endl; - SET WIDTH DOUBLE D = 33.11444; cout << setPrecision (4) << D << endl; ---- Set the number of digits of the decimal point COUT << DEC << 10 << endl; ---- once set, the following follows. COUT << Hex << 10 << endl; cout << Oct << 10 << endl; setbase (n); --- Change the original settings. If it is changed to 16, setbase (16); int A; cin >> HEX >> A; ---- In HEX input cout << DEC << a << Endl; three, memory alignment problem (keyword, Memory alignment) Typedef struct {int a [10]; char ch [10]; int F [10]; BOOL B [10];} mtype;

INT _TMAIN (int Argc, _tchar * argv []) {

INT i; mtype mt; printf ("% d", sizeof (mtype)); getCH (); Return 0;} This structure is originally calculated as 100, however, resulting 104. DEV C under VC and Linux is all. The reason is that the memory is the problem. The general compiler considers that memory is aligned with a multiple of 4. Carefully analyze the memory can be concluded, not enough 4, move back, make up a multiple of 4. An object of this institution involves 2 bytes of backward movement, complement 2 bytes. So 104. You can add #pragma pack in front of the file (1) this is to align the multiple multiple of the compiler to 1, so that the length is 100.

four. Point definition type definition typef unsigned char _uint_8; typef struct {char LO4: 4, // first defined is low, in memory, high in left, low in right. Hi4: 4;} mybyte; int main () {

Mybyte mch; void * p; //mch.hig4 = 6; //mch.low4 = 1; p = & mch; // * ((unsigned char *) p) = * ((unsigned char *) P) >> 4; * (unsigned char *) (p) = 0xf1; Printf ("% d / n", mch.hig4); // - 1 result printf ("% d / n", mch.low4); // 1 * (unsigned char *) (p) >> = 4; Printf ("% d / n", mch.hig4); // 0 Printf ("% d / n", mch.low4); // - 1 return 0;} Indicates that one byte is divided into two parts, with 2 digits in front, and 6 bits behind. use:

MyByte B; B.HI4 = 10; B.LO4 = 2;

COUT << b.hi4 << endl; cout << b.lo4 << endl; Note: You cannot define. It must be defined in the structure.

V. About New

New "allocation" memory is of course in a heap. But NEW does not only have the role of allocating memory, and it can also enforce the role of re-constructing objects on existing memory (including stack memory).

#: #Include using namespace std;

Class a {public: Int i; int j; a (int _i, int _J) {i = _i; j = _j;}}

Int main () {a a (3, 4); cout << a.i << a.j << endl; new (& a) a (5, 6); cout << a.i << a.j << endl;

Return 0;}

Sixth, the problem of n random numbers and the algorithm of n.

Void myran (int N, int m) {INT i; int sum = 0; int * a = new int [m]; for (i = 0; i

Assignment of the structure: For the two structures above: typedef struct {Int a; short b [2]; / * Define the first structure * /} EX2; typedef struct ex1 {int A; char b [3]; EX2 C; / * Defines the second structural * / ex1 * d;} EX1; the above is the definition method of C language, in C , you can omit the TyPedef, such as: struct ex1 {int a; char b [3] EX2 C; / * Define the second structural * / EX1 * D;}; then, the C compiler can identify EX1 and can be directly defined using an EX1 definition object without adding Strcut. For example: EX1 E1;

So the key to see what compiler, I have no errors with G compile. There is a lot of errors in GCC. It can be seen that C supported later. There is an explanation in C programming ideas. CH2, P12 can assign a value. EX2 E2 = {10, {10, 10}}; EX1 E1 = {10, "Hi", {5, {25, 25}}, 0}; eight, about memory issues: from the overall program memory space Divided into code areas and data area. From the perspective of C , it can be divided into the data area: 1. Automatic storage (stack): Automatic (local) variable, register variable (declared register variable may be in the register, may also be in general memory. Logic The host register belongs to the automatic storage area.), Temporary objects, and function parameters. 2. Static storage area: Static variables in the global object, static variables in the class, static data members, constant strings, and namespace variables (such as Namespace ABC = STD; "ABC.) 3. Free storage (Heap): Also Dynamic memory.

There is such an executable, .o, .a file, the system specified in the system has so much * .BSS This SECTIOPN holds uninitialized data, which exists in the program memory image. By definition, when the program starts, the system initializes those data 0. This section does not account for file space, just as its section type SHT_NOBITS indication. * .comment This section saves version control information. * .data and .data1 These Sections saves the initialized data, and those data exist in the program memory image. * .debug This section saves information for the label debugging. This content is not specified. * .dynamic This section saves information about dynamic connection. The properties of this section will include a SHF_alloc bit. Does SHF_WRITE are related to the processor. The second part has more detailed information. * .dynstr This section saves the string required to dynamically connect, in general, the name string associates the entrance of the symbol table. The second part has more detailed information. * .dynsym This section saves a dynamic symbol table, such as a description of Symbol Table. The second part has more detailed information. * .fini This section saves the executable instruction that constitutes the termination code of the process. Therefore, when a program is exit, the system schedules the code in this section. * .got This section saves the global offset table. See the "Special Offset Table" of the "Special Offset Table" in the first part. * .hash This section saves a label has a hash table. Look at the second part of "Hash Table" to get more information. * .INIT This section saves the executable instructions that form the initialization code of the process. Therefore, when a program starts running, the system schedules the code in this section before the main function is called before the MAIN function is called. * .INTERP This section saves the path of the program's interpretator. If there is a loaded segment in this section, the SHF_alloc bit of the properties of this section will be set; otherwise, the bit will not be set. See the second part to get more information. * .LINE This section contains the number of row information of the character, which describes the relationship between the source program and the machine code. The section content is not clear. * .note This section saves some information, using the format mentioned in the "Note Section". * .plt This section saves the Procedure Linkage Table. Look at the first part of `` specialsections '' and the second part of "Procedure Linkage Table". * .rel and .rela These sections saves the information of the positioning, and looks at the following `` Relocation '' description. If the file contains a loadable segment, and this segment is relocated, the properties of this section will set this, a relocation section is applicable to .Text, then the name is .rel.text or. RELA.TEXT. *.RODATA and .RODATA1 These sections hold read-only data to construct unwritable segments in the process image. Look at the second part of `programheader '' get more information. * .shstRTAB This section saves the section name. * .stab This section saves a string, typically, the description of the string of the name and the entry of a label are associated.

If the file has a loadable segment, and this segment includes a symbol string table, then the SHF_alloc property of the section will be set; otherwise it is not set. * .symtab This section saves a symbolic table, as described in this section `` symboltable ''. If the file has a loadable segment, and this section contains a symbol table, then the section's SHF_alloc property will be set; otherwise it is not set. * .text This section saves the program's `` text '' or is an executable instruction. The prefix is ​​a point (.) The section name is the system reserved, although the application can use those Section names. Applications can use non-prefixed names to avoid and systematically conflict. The Object file format allows a defined section portion that does not appear in the list. An Object file can have multiple sections of the same name. Quote: Simply speaking, the following structural command line parameters and environment variable stacks are not initialized data segment BSS initial data segment

The C program has been consisting of the following parts:

1) Text section - CPU execution machine; one program has only one copy; read-only, preventing procedures to modify its own instructions due to accidents; 2) Initialization data segment (data segment) - all assigned in the program The global variable of the value is stored here. 3) Non-initialization data segment (BSS segment) - There is no global variable in the program; the kernel initials this segment into 0.4) stack-growth direction: from top-down, automatic variable and each function call The information you need to save (return the address; environmental information). 5) Heap - Dynamic storage.

| ----------- || || ----------- || Stack || ----------- || | || / | / || || || / | / || | || ----------- || Heap || ----------- || Not initialized || --------- || Initialization || ----------- || Text section || ----------- |

http://community.9cbs.net/expert/topic/3215/3215569.xml?temp=.3182337

Low address -------------------------------- | _Text Class 'CODP' | | CODE | --- ----------------------------- - | _Data class 'data' | | Initialized Data | ------ -------------------------- DGROUP | _BSS Class 'BSS' | | Uninitialized Data | ---------- ---------------------- - | | | Free Space | ------------------------------------------------------------------------------------------------------------------------------------------ -------------- | | | STACK | ----------------------------- --- | | | HEAP | ------------------------------ | | | Free Space | -------------------------------- High Address nine, how can I quickly detect the dead chain in a huge linked list? I really didn't think of a good way, I can only say, there is no way, I can only have one more ... Do you have any good way? Dead Chain: NEXT pointer of a contact of the linked list points to the contacts that have appeared, resulting in a linked list. Just forgot to say: The chain list is a single-strand.

Old solution, very cattle: the answer to the simplified version of this question, I will post it again, huh, huh. If it is just a way to determine if there is a loop in the linked list, there is a way to make a way. Open two pointers of the two trails, take a junction one, another walk forward, when these two pointers meet, if the next NEXT == Null, there is no loop, otherwise, There is a dead chain.

10. Information about the handle, see C programming ideas CH3, P12.

First, in order to divide people, I am on the high building, and I am on the high-rise building. It turns out that everyone is upstairs.

Second, the value of the array: struct node {int N; float f; char ch;}; int main () {int STR [20] = {1, 50, 3}; // The remaining element is 0. As long as there is, the remaining is 0; //, if there is no initialization, int STR [20]; this, the array does not initialize 0. Instead, any value node nodearr [20] = {{1, 1.1, 'a'}}; // In the case where the constructor is not constructed, the remaining nodes are initialized to 0. In addition to the first node, the next element {0, 0.0000, 0} INT i; for (i = 0; I <20; i ) {Printf ("% D", STR [I]); printf ("% D% f% C / N", Nodearr [I] .n, Nodearr [i] .f, nodearr [i] .ch);} printf ("/ n"); return 0;}, In the case of the constructor, the usage is different above: struct node {int N; float f; char ch; node ();}; node :: node () // default constructor {n = 1; f = 1.1; CH = 'b';} int main () {// int STR [20] = {1, 50, 3}; // node nodearr [20] = {{1, 1.1, 'a'}}; // This kind of use is compiled, requiring constructor to construct the object node noder [20] = {}; // Each Node object calls the default constructor, the internal members are // 1, 1.1, 'b' // visible: if Without constructing, it is compiled with the same syntax as C, // If there is a constructor, it must be initialized with a constructor. Here is the same INT i; for (i = 0; i <20; i ) {// printf ("% d", str [i]); printf ("% D% f% c / n ", Nodearr [i] .n, Nodearr [i] .f, nodearr [i] .ch);} printf (" / n "); return 0;}

Four, an interesting interview question: Where can the master can help me, do not use the IF, While, Do ~~ while, do not use the relational operator, do not use max (), min (), how The size of the two numbers of the inputs are included. (Note: Implementation does not know the size of the number of inputs) Float Max (float a, float b) {Float T1, T2; T1 = A B; T2 = SQRT ((ab) * (ab)); // Solve You also said that in Fabs, it also used judgment statements Return (T1 T2) / 2;} It is a good reason here. T1 is the sum, T2 is a large part of the smaller. If the part of the large out is added to the traum, it is exactly twice the big person.

Third, regarding the definition of the default parameters. If a program has only one CPP file, and this function does not have a function sound name, only function definitions, then the provincial deficient parameters of this function can be placed in the function definition. For example: this situation: #include using namespace std; void fun1 (int m = 3, char ch = 'b') {} int main () {fun1 (); fun2 (); return 0;}

If a program, there is a function sound name in the header file, or there is no header file, but there is a function name, the provincial deficiency parameters must be placed in the function name, and cannot be placed in the function definition, otherwise compile error. For example: //links.hvoid fun2 (int m = 3, char ch = 'a');

//links.cpp#include #include "links.h" Using Namespace std; void fun1 (int m = 3, char ch = 'b'); // has a name, must give the provincial lack at the reputation Parameter void fun2 (int m / * = 3 * /, charch / * = 'a' * /) // is given, no longer set the provincial deficiency parameter {} void fun1 (int m / * = 3) * /, CHAR CH / * = 'b' *) // The audition is given in the definition, no function is set in the definition parameter {} void fun3 (int m = 3, char ch = 'c') // no function Name, you can give the provincial missing parameters when defined {} int main () {

FUN1 (); fun2 (); fun3 (); return 0;

Fourth, distributed system distributed systems are interconnected by communication networks to physically distributed data processing systems or computer systems, implement information exchange and resource sharing, and collaborate completion tasks. Distributed systems require a unified operating system to achieve system operation. Distributed Operating System Manage All resources in the distributed system, it is responsible for the full system resource allocation and scheduling, task division, information transmission control coordination, and provides users with a unified interface, users need to achieve this interface Operation and use system resources, as for which computer is executed or using which computer is used, the user is done, the user does not have to know. In addition, due to the distributed system more emphasizes distributed computing and processing, there is a higher demand for multi-machine cooperation and system reconstruction, robustness and fault tolerance, requiring distributed operating systems to have a shorter time, higher throughout Quantity and higher reliability.

V. Bubbling Sort Algorithm: Void Order (Char * CHS, Const Int & n) {// Bubbling Sort Algorithm, ZHANGGGDLT INT I, J; Int MaxSubscript; for (i = 0; i

Eight, enumeration type definition, the value of enumeration elements can be repeated. Typedef enum {monday = 1, cat, tuessay = 1, dog} week; usage: Week W = Dog; int K = TuesDay; above is possible.

At this time, the value of the DOG is the value of its front, and there are two elements values ​​in it. Similarly, CAT is the same. The values ​​of CAT and DOG are 2.

Nine, get the time, including the week program #include #include

INT main () {char * wday [] = {"Sun", "MON", "TUE", "WED", "THU", "fri", "sat"}; time_t timep; struct TM * P; TIME (& TIMEP); P = localtime (& TimeP); / * Get local time * / printf ("% d.% d.% d", (1900 p-> tm_year), (1 p-> tm_mon), p -> TM_MDAY); // Take note of Month LOCALTIME from 0. . 11 represents 1 to December, so add 1. Printf ("% s% d:% D:% D / N", WDAY [P-> TM_WDAY], P-> TM_HOUR, P-> TM_MIN, P-> TM_SEC); Return 0;}

Ten, each analysis #include using namespace std;

Class a {int x;};

Class B: PUBLIC A {public: int B1; b () {b1 = 2;} int geti () {cout << "Geti Called, B1 IS" << b1 << endl; return 1;}}; int main () {A a; b b; int K; b * pb = (b *) & a; pb = (b *) & k; pb-> geti (); int i; cin >> i; returnography;

}

Analysis: Your class A is a base class, class B is a subclass. The address of the object A of the base class is forced to convert the address of the subclass. This is very dangerous, which will cause data to cut. In fact, it is even better to do this. Forced type conversion, you can convert any types, although there is no error in the syntax, but it is meaningless. For example: we can int K; b * Pb = (b *) & k; there is no error like this, but it is more meaningless.

Your conversion is also a truth. In your A object, there is no thing you want to use, but for the computer, it doesn't matter if it is, it will operate the memory fingered by the pointer. It is considered to start from the position finger from the pointer. Later, it is a Class B object. So compile can pass. But there is no meaning.

First, Digital Capacity Algorithm DES (Data Encryption Standard)

Second, under Linux, when it is connected to executable, if the connection is a general .o file, the content of the entire file will be loaded into the executable; if the library is connected, it is just from the library. The variables and functions used in the program will load them into the executable, those variables and functions referenced in the library but are not referenced by the program are not connected to the executable. So the library can save a lot of development time, when writing larger programs, put the program module in the library.

Third, one type problem int packetinfo :: packetlen (const void * packet) {u_int_8 tempbyte [4]; // use to store, Exchange the info from thepacket int rtype; int packetlen = 0; memcpy (Tempbyte, (U_INT_8 *) Packet 12, 2); ...} I have to implement memory copies in my function, the prototype of Memcpy is defined function void * memcpy (void * dest, const void * src, size_t n); I started Memcpy (Tempbyte, Packet 12, 2); Compilation Report error, later replaced with memcpy (void *) packet 12, 2); nor, the original error is in an empty type pointer and a number phase Plus, you cannot get the size of the type of the type, so you can't determine the address of the packet 12. Another example: void mecopy (void * DP, const void * sp, int num) {INT i = 0; While (i

Fourth, in C , the function does not have a hierarchical relationship, and there can be the following function call. Void funb (); void funa () {funb ();} void funb () {funa ();} You can say that the called function is called before the function call is called.

5. The use of the inline function is limited to the number of internal functions is to improve the function execution efficiency (when used in the inline function, the function call is not performed, but is similar to the macro replacement), the inline function definitions have a limit. 1. There is no static variable 2 in the function. The function is not too complicated in the function. No Switch, Goto and other statement 3, can not be recursively 4, and the array cannot be defined. If the above situation occurs, the compiler will automatically ignore inline to compile it as a general function.

Sixth, in memory, the number is in the form of complement, the complement of the integer is still an integer, and the complement of the negative number is the positive number (including symbol bits) to add 1. For example: #include int main () {char CH = -3; / - 1: 11111111 -2: 11111110 -127: 10000001 -128: 10000000 Unsigned char value; for (int i = 0; i <8; i ) {value = ((CH << i) & 0x80) >> 7; // 11111101 Printf ("% d", value);} printf ("/ n"); return 0;}

Seven, Linux IP address conversion function: #include #include #include

INT INET_ATON (Const Char * CP, Struct In_Addr * INP);

IN_ADDR_T INET_ADDR (Const Char * CP);

IN_ADDR_T INET_NETWORK (const char * cp);

Char * inet_ntoa (struct in_addr in);

Struct in_addr inet_makeaddr (int NET, INT HOST);

IN_ADDR_T INET_LNAOF (Struct In_Addr IN);

IN_ADDR_T INET_NETOF (Struct In_Addr IN);

7. About the comma operator int T; int i = 0; t = i , i, i ; // result t = 1; i = 3; Said in C textbook, comma operation is forced from left to right . The value of the entire statement is the last minute operation. For example: int A = 3; a = 3 * 5, a * 4; // The result of the statement is 60 (a = 3 * 5, a * 4), A 5; // The result is 20INT a = 2, B = 3, C = 4; Print ("% D,% D,% D / N", (A, B, C), B, C); the first integer of printing is (A, B, C), Its value is the last one, so C, the last answer is: 4, 3, 4

That is, the above statement is divided into four parts, the first portion is t = i , the second portion is i, the third portion is i . There is also the following example: int A [] = {1, 2, 3, 4, 5}; int * i = a, k; int b = 0; b = k = * i , Printf ("% D ->", k), k = * i, printf ("% D- > ", K), K = * i , Printf ("% d -> / n ", k); Printf ("% d / n ", b); output is: 1-> 3-> 3-> 1 (Finish). Seven. One (related above, Printf () Weird) int Array [5] = {8, 5, 13, 55, 6}; int * p = array; printf ("% D,% D,% D / N ", * p , * p, * p ); printf ("% D,% D / N ", * P, * p); for (int i = 0; i <5; i ) Printf ( "% d,", array [i]); the result is: 13, 13, 856, 568, 5, 13, 56, 6, very intimate, and later summarizes. Find the answer, and discuss the conclusions discussed by a classmate. In the C function, the function is in the stack, the parameter is hit from right to left, such as: VoID PP (INT A, INT B, INT C) {INT D; INT E; D = 0; E = 2 } int main () {... pp (...);} At this time, there is a PP parameter, main return address in the stack of the function PP, and on-site information. The parameter stack of PP is: C, B, A. In this way, first press c, then count C, that is, the last parameter is first, for the function Printf ("% D,% D,% D / N", * p , * p, * p ); For the first time, one * pp is first, determined by 0 (the last parameter), then count one * P draws 2 (B) one parameter), and finally count the first * p (A first Parameters) Dead 2. So a = 2, b = 2, c = 0. It is 220.

It seems that if each change is involved in each change, the output is to fall.

Seven. On the format of Printf () Printf, if the / 0 / digital (1 to 3 digits) / x number appears (1 to 2 digits of hexadecimal). / 0 Of course, it is the end of the string. / 101 At this point, / represents a character with 1 to three binary numbers behind. Note that it is calculated according to the eight-input, not a decimal. / x61 / indicates a character with hexadecimal. Printf ("/ 101 / x41"); the result is: a a

Eight, about sizeof problem

Void func (Char A [100]) {char b [100]; Printf ("% D / N", sizeof (a)); // 4 bytes rather than 100 bytes of Printf ("% d / n", SIZEOF (B)); // 100} Analysis: Two, the cause of the unused, to track the problem of the function of the function. When the array is incorporated into the function, this array is incorporated as a pointer, that is, the transmitted address. So the front is 4, not 100. Nine, the combination of symbols. In C , the operator generally binds from left to right, only the assignment is a special case, combined from right to left. For example: A B C * D combined with left to right binds A = b = c = D; binds from left to right.

Ten, Round , - Operation. INT i = 3, K; K = ( i) ( i) ( i); K's value is 18. The reason is that each operand is first , and finally calculates. I three times into 6, and finally three six-phase plus, get 18INT i = 3, K; K = (i ) (i ) (i ); the result is 9. The reason is that i is calculated first, three three-phase plus, last , i = 6.

First, in the C language, all of the types do not add functions, and will automatically press integration. In a function, if the return type is different from the function type, the value of the data type conversion can be automatically performed with the value type, and the function type determines the return type. As follows: max (x, y) {float x, y, z; z = x> y? X: y; return (z);} main () {float a, b; int C; scanf ("% f, % F ", & A, & B); C = Max (A, B); Printf (" MAX IS% D / N ", C);} The result is: 1.5, 2, 5mAX IS 2max (x, y) is not obvious Define types, press integrity, return must be integrated. In the C function, if there is no return type and return, this is not to say that the function is really no return, but to return a user useless value, this value is uncertain. For example: //test.c#include #include pp () {} pp1 () {} main () {INT C = 0; c = pp (); printf ("% D / N ", c);

C = pp1 (); Printf ("% d / n", c);} The output is: 02 is uncertain. If the function does not want to return, use the VOID to define the function type. This will not return a value.

Second, the general form of C function definition: no argument function definition: Type identifier function name () {Description section statement}

General Forms with a DEVeritance Definition: Type Identifier Function Name (Form Parameter List) Form Parameter Description {Description Some statement}, such as: int MAX (X, Y) INT X, Y; // Form Parameter Description Part {INT Z; // Description section in the function body z = x> y? X: y; return (z);}

Function Call Description: If the function parameter list contains multiple arguments, each system is uncertain for the order of the real-argument, and some systems are in the right order, some from the left, many C versions. (Turbo C and MS C) is the order in order to left from the right left. This leads to the previous Printf ("% D% D% D / N", * P , * p, * p ); conclusions. Third, the macro defined range #define G 9.18 ^ | | G. Effective area. | V

#undef g Macro definitions cannot be added to the partition, otherwise the semicolon is part of the macro definition. Macro definitions do not do type checks, during precompile time processing, only if the expansion will decide whether it is correct.

Fourth, the local variable VOID PP (Char str1 []) {INT i; for (i = 0; i <10; i ) PRINTF ("% C", * STR ); // 1 char str 20]; for (i = 0; i <10; i ) Printf ("% c", * str2 ); // 2} In this function, the parameter STR1 of the function is an array, and the local variable STR2 of the function is also one. Array. But at 1, the compilation is correct, but at 2, the compilation pass is not. They are all arrays, but if the function parameter is an array, then as the address processing, STR1 can be processed as a pointer variable. You can use the address of operation, but for local variables STR2, STR2 is an array, and the address of the array is a constant, which cannot be . This is a truth with the example of the SIZEOF mentioned above. Void PP (int STR [10]) {Printf ("% D / N", sizeof (str)); // 4 is just the address. INT STR2 [10]; Printf ("% D / N", SIZEOF (STR2)); // 40 array size. }

V. Pointer to the function of the function. The general form is: Data type (* pointer name) (parameter linked list); in C language, the parameter linked list is not required, only needs to be called during call. However, the C must be required to give a parameter lin list when the function pointer is defined. For example: //test.c#include #include void pp (int a) {printf ("ok / n");} int main () {void (* p) () (// C function pointer definition, may not write a parameter linked list, no error. C is not. P = PP; // When assigning a value to the function pointer, you only need to give a function name without having to give parameters (* p) (); // through the function node call function return 0;}

//test.cpp#include #include void pp (int a) {printf ("ok! / n");} int main () {Int a = 3; void (* p) (); p = pp; // error, must define: void (* p) (int); // p = p1; (* p) (a); return 0;} C definition is not strict, but C is strict, the same, the function of C may not define the return type, but C must be defined. Sixth, the function pointer performs function parameters to pass the function name as the parameter to a function, this is: more flexible, such as a function SUB needs to call both functions, if you call it directly, then the SUB function is written. If you want to call any two functions in the SUB, use the function pointer to do the parameters, and different functions can be called depending on the assignment. For example: SUB (INT X, INT Y, INT ()); {.... (* fun) ();} .... int fun1 () {...} main () {int A, B; SUB (A, B, FUN1);

7. Regarding the definition of the joints of the pointers and arrays:

INT (* Pointer1) [4]; int * Pointer2 [4]; see the difference: the front Pointer1 is a pointer to a one-dimensional array of four elements; back Pointer2, one is defined with four elements One dimensional pointer array, each element of the array is a pointer variable.

8. Talking about the callback function

This is a mechanism that is similar to different functions that are consistent with the same return value parameter type according to different conditions.

For Windows Message Mechanism General Tune Function Function Window Functions, use this window function according to different messages. It can also establish a corresponding message mechanism for users, and events like VB. 1. Declare a function pointer 2. Provide a function of functionality to initialize the function pointer to the corresponding implementation function to register to the caller 3. When the specific event / condition occurs, the caller is called using the function pointer. This is the general mode of operation of the callback function, In fact, if you learn COM, you will find that the ConnectionPoint is also conducted by this way. The client registers its own event handling subripes to the service team components, the components trigger events by calling these functions, in fact, the essence of the callback is your function. Form (return value, parameter) I provide implementation and specific call addresses.

Nine, an example of the callback function: //test.cpp#include typef void (* pcb) (int); // In order to simplify the variable definition of the function pointer type, improve the program's // readability, We need to customize the function pointer type. Void PP (INT A), the callback function can be called like a normal function, {//, but only it is called a callback function when it is passed as a parameter to the modulated function. Printf ("OK!% D / N", A);

Void Called (int N, PCB P) // is called by the user program, so the called is called the function {// I think so, the user is calling the above function, // Need you to implement a PCB Type of callback function: Printf ("okk"); (* p) (n);} int main () {int N = 1; called (n, pp); // Put PP as a variable to the called function Return 0; Getn (int N) // This member must be static, otherwise compiling error {Printf ("ok get! / n");}}; VoID PP (INT N, PCB P) {(* p) (n); } int main () {a a; int N = 3; PP (N, A.GETN); return 0;}

Reference: http://www-900.ibm.com/developerWorks/cn/linux/l-callback/index.shtml (to be continued)

转载请注明原文地址:https://www.9cbs.com/read-110273.html

New Post(0)