C / C actual programming common problem analysis
----- Xi'an University of Posts and Telecommunications Computer Xu Zhaoyuan (Flxyzsby@163.com)
[Summary] This paper analyzes the problem of C / C actual programming and easy encounter.
In the learning programming and course internship, we will encounter a lot of problems on programming, which is generally more messy. These issues are summarized below.
1. Contourment and Different Differences with #define
(1) #define for C and C , const for C
(2) #deinfe is the macro definition, you can define constants such as #define n 100,
You can define a function #define max (INT A, INT B) (A> B? A: B), you can define the formatting operation #define out "% D% D / N" You can freely define the constants you need to replace, functions Wait, its purpose is to reduce the same but cumbersome code you repeated in your code.
(3) Const usage is more complicated, summarized as follows:
const Int Arraysize = 100; // Modified constant, this constant must initialize
CHAR CHAR_A = "C "; // char_a content can be changed in subsequent programs, re-assay char_a = "c"
const char char_b = "c_c "; // String CHAR_B content cannot be changed
Char * const ptr_a = & char_a; // often pointer, pointer itself cannot be modified
Char const * ptr_b = & char_b; // Point to the length of the pointer, the content pointing by the pointer cannot change the constet char and char constings effects.
Const char const * ptr_c = & char_b; // Pointing to constant normally, both cannot be changed
Void function1 (const var_type var); // Function parameter is passed, and const will guarantee that VAR is not changed.
Void Function2 (const var_type * var) or void function2 (const samepe & var) // function parameter is delivered, const will guarantee that the address content is not modified
Const var_type operator * (const var_type & a, const var_type & b); // Return value cannot be changed, protect return value
Const var_type * function () // Let function return to point to Const, the content of this address will not be modified
Void class_memberFUntion (***) const // The member function of the class indicates that this member function cannot change the value of any data type.
(4) #define is a pretreatment command, and it is only a text replacement when macro. There is no type of check, and the definition function does not have a series of operations such as the stack, code generation, on-site protection, on-site recovery, but it is reduced. Space and time overhead, the efficiency is high.
The following example is what we often make:
#define max1 (a, b) ((a)> (b)? (a): (b))
INT A = 5, b = 0;
Max ( a, b); // a value increased by 2 times
MAX ( a, b 10); // a value only increases 1 time
If you understand, if you carefully observe, you will find that Define has brought us much trouble! (If you want to know more, take a look at "Effective C ")
2. C / C memory allocation?
(1) Allocate memory from the heap, use Malloc (Calloc) and Free, using new and delete in C
(2) The object to allocate memory is a pointer, which cannot be made with Malloc / delete, new / free, which is illegal.
INT LEN = 10;
Char * p_char;
p_char = (char *) Malloc (SIZEOF (CHAR) * (LEN 1)); // CERE FREE (p_char); // Delete the content points to the pointer, that is, memory, p_char points to null, and cannot be accessed later it
P_CHAR = New char [len]; // C operation
Delete [] p_char; // Whenever you use "[...] in the" New "arithmetic, you must use" [] "in the" DELETE "statement. This syntax is necessary because "Indicators" pointing to a single element "and" indicators pointing to an array "are unable to distinguish between syntax.
(3) Malloc / free than C Malloc / Free is more advanced, the New operator automatically determines the correct length of the object and returns the correct type of pointer. And Malloc requires sizeof () to manually determine the length of the object, so you may More functions need to increase complexity, Malloc needs to use the forced converter (var_type *) to return the correct type pointer.
NEW can initialize when allocating memory, Malloc can't.
p_char = new char ("C ");
More importantly, when using the non-internal data type object, the New automatically calls the constructor of the generated object, and the DELETE automatically calls the destructor of the generated object.
3.TC/BC Character programming problem?
(1) TC / BC divides the screen into two state text window mode and graphics window mode. The system is in text mode by default.
(2) Working screen into 80 (or 40) line 80 columns in text mode, we can make normal character programming, but you can also use the following screen operation function:
Void WINDOW (int LEFT, INT TOP, INT RIGHT, INT BOTTOM); // Settings Window
Void textbackground (int color); // background color
Void textcolor (int color); // text color
void textttr (int attt); / / Set the text of the text and background colors
Void ClrsCr (Void); / / Clear the text content in the current window and position the cursor in the upper left corner of the window (1, 1)
Void Clreol (Void); / / Clear all characters from the cursor position to the end of the current window, the cursor position is unchanged.
Void gotoxy (x, y); // This function is useful, it is used to locate the cursor in the current window. Here X, Y is the coordinate of the cursor to be positioned (relative to the window), when X, Y exceeds the size of the window, the function does not work.
INT GetText (int XL, int yl, int x2, int y2, void * buffer);
INT PUTTEXT (INT X1, INT Y1, INT X2, INT Y2, VOID * BUFFER);
INT MoveText (int X1, int x2, int y2, int x3, int y3);
Please refer to << BC library function >>
(3) To use the TC / BC graphics mode, you need to do the following:
<1> Make sure there is a display graphics driver * BGi in your TC / BC directory, select the graphics lib in the integrated development environment options / linker, only in this way ensures that the graphic function is used correctly.
<2> #include in the code contains graphics.h header files
<3> Initialize the graphic screen.
We need to use before using the graphic screen
Void Far Initgraph (int Far * GDRIVER, INT FAR * GMODE, CHAR * ATH);
Function initialization screen
Where gDriver and gmode indicate graphics drives and patterns, Path refers to the directory path where the graphics driver is located.
The first two parameters have a lot of options, you can refer to the relevant reference. We can usually use the following universal functions to initialize our college and now most of the microcomputer graphics mode.
Void myinit (void) {INT GDRIVER = Detect, gmode = 2; // detect is an automatic detection display
INITGRAPH (& gdriver, & gmode, "// bgi");
}
Call Myinit () can initialize the screen when you need to initialize.
Note: Using the graphics window, it is best to use Closegraph () to close graphics mode
After the initialization screen, we can use the graphic operation function such as:
Void Far Putpixel (INT X, INT Y, INT Color); // Draw Point Function
Void Far Line (int X0, int y0, int x1, int y1); // draw straight line.
Void Far Lineto (INT X, INT Y); // Painting a straight line from the current cursor to point (x, y)
Void Far Circle (int X, int y, int RADIUS); // draw a circle
Void Far Arc (int X, int y, int standi, int endangle, int RADIUS); // draw a circular arc
Void Ellipse (int X, int y, int tentius, int yradius); // Draw an ellipse
Void Far DrawPoly (int Numpoints, int far * polypoints); // Painting polygons
More functions see "BC library function"
(4) There are some differences in the operation of the text in graphics mode and text operations in text mode.
In graphics mode, you can only use standard output functions, such as printf (), PUTS (), PUTCHAR () function output text to the screen
In graphics mode, the system will make a function of the text of the text:
Void Far Outtext (Char Far * TextString); // Current location output
Void Far Outtextxy (int X, int y, char far * textstring); // output to (x, y)
Void setColor (int) // Character color
Void Far setTexjustify (int horiz, int vert); // Used to locate output strings
Void Far SetTextStyle (int Font, int Direction, int CHARSI); / / Set the shape of the output character
Void Far SetuserCharsize (int Mulx, int Divx, int mu; // set stroke type and magnification
See "BC library function"
4. Question of the console program under VC
(1) Students of the beginner VC always try to transplant the procedures under TC or BC to VC, but they find that the big procedure cannot run. First, TC / BC and VC are not compatible with each other in different companies. Secondly, The header of the TC / BC is not necessarily or not in the VC, so they differ from the processing functions of the same problem, or the parameters. At time, don't expect VC console applications to provide you with what graphics operation, unless You will with your MFC and OpenGL.
(2) until now, I only have the color of the console program with the color of the text, with the following API functions: getstdhandle () and setconsoletextAttribute (), function original
Handle getstdhandle (DWORD NSTDHANDLE);
Bool setConsoletextAttribute (
Handle HconsoleOutput, // Console screen buffer handle
Word Wattributes // Color of text and background
);
Writing the following subunies can change characters color
Void SetColor (unsigned short forecolor = 4, unsigned short backgroundcolor = 0)
/ / The default value for the parameter, so that it can accept 0/1/2 parameters
{
Handle hcon = getstdhandle (std_output_handle); // This example is an example
SetConsoleTextAttribute (hcon, forecolor | backgroundcolor);
}
Call this function in the required place.
[Postscript] Confidence, you can only discuss these questions. If you have more questions, please issue a problem or E-mail to flxyzsby @ @Ttp://202.117.133.118/bbs programming module 163.com, I will give you a detailed answer.