Summary of C language knowledge points (the most complete version) quick collection
Yang Hengchang 2021-02-23 10:13:35


C Summary of language knowledge points ( The most complete edition ) Collect it quickly


The first part "C Basic knowledge of language " Knowledge point

1、C The basic structure of the program C A program is made up of functions . Each program consists of one or more functions , There must be and only one main function main( ). main Function is an executable C The entry and normal exit of a language program , No matter where it is written in the whole program . stay C In language , There is a difference between upper and lower case letters .( For example, we are used to using lowercase letters to define variables , Use capital letters to define constants ). C There are two ways to annotate a program , One is line comment , Use "//"; The other is block annotations , Use "/* */", Be careful

"/*" And "*/" You can't nest . C The language writing is more flexible , But it is advocated to use the indent format for program writing , To reflect the sense of hierarchy between sentences . C Each statement of the program is marked with " A semicolon " As an end sign . Semicolons are not allowed in the following cases :

(1) You cannot use a semicolon after the defined function name ; (2) if…else… Sentence is a whole , You can't separate them with semicolons in the middle ; (3) Semicolons cannot be used after precompiled commands .

2、C Procedure development steps

C The development process of language on computer mainly consists of the following four steps : First step : edit . The generated suffix is ".c" The source file The second step : compile . The generated suffix is ".obj" The target file of The third step : Connect . The generated suffix is ".exe" The executable of Step four : function .

3、VC++6.0 Use of development tools

Press the function key Ctrl+F7 compiler ; Press the function key F7 Connector ; Press the function key Ctrl+F5 Run the program ; If the program has syntax errors in the process of compiling and linking , Press the function key F4 Locate the error line and correct the error according to the error message ( The principle is to solve first error, Solve again warning).

4、C Naming rules for identifiers in languages

Identifiers are made up of letters 、 Numbers 、 Underline composition ; Specifies that the first character must be a letter or an underline . Identifier defined variable name 、 Function name 、 Constant names and so on are best done " Know what you know "; Case means different ; Can't make

With keywords ; It's better not to talk to C The library function of language has the same name .

5、C The data type of the language

C The data type of language consists of basic type and complex type . The basic data types include character type (char)、 integer (int,short,long)、 Real type (float,double); Complex data types include pointer types 、 Array 、 Structure 、 Consortium .

char Type occupation 1 Bytes 、short Type occupation 2 Bytes 、long The type and float Type occupation 4 Bytes 、double Type occupation 8 Bytes .

6、 Constant

(1) Character type constants ( A character enclosed in single quotation marks ) Two forms —— Ordinary character 、 Escape character ( master '\n'、'\0'、'\t'、'\\'、'\''、'\"'、'\ddd'、'\xhh') Regardless of ordinary characters , Or escape characters , Are equivalent to 0-127 Some integer between , namely ASCII clock .

(2) integer constants Three representations —— Decimal form 、 Octal form ( Add leading 0)、 Hexadecimal form ( Add leading 0x) Be careful :C There is no binary representation of integer constants in a language .

(3) Real constant Two forms of expression —— Decimal representation 、 Exponential representation ( from " Decimal number "+"e or E"+" Decimal integer " form , Be careful :e or E There have to be several sides of it , It must be followed by an integer )

(4) String constant ( Zero or more characters enclosed in double quotation marks ) The compiler adds... At the end of the string '\0' As the terminator of a string . Compare 'a' and "a" Different .

(5) Symbolic constant : for example #define PI 3.14159

7、 Variable

Variables must be " First define 、 After use ". Variables represent a certain amount of storage space in computer memory , How many bytes does it represent

Storage space depends on the type of variable , The data stored in the storage space is the value of the variable . Be careful : If the initial value is not assigned after the variable is defined , Then the initial value of the variable is a random number . So variables should be assigned before they are used . by

Several methods of variable assignment :① initialization ;② Assignment statement ;③ Call the standard input function to assign values to variables from the keyboard . (1) Character variables

use "char" Define character variables , The character type variable stores 1 Number of bytes . For an unsigned character variable , The value range is 0~255, For signed character variables , The value range is -128~+127.

(2) Integer variables use "int"、"short"、"long" Defining integer variables , among int The type and long Type take up 4 Bytes of storage space ,short Type take up 2 Bytes of storage space .

(3) Real variable use "float"、"double" Define real variables , among float Type take up 4 Bytes of storage space ,double Type take up 8 Bytes of storage space .

8、 expression

Expressions have a wide range of meanings , Depending on the operator , There are assignment expressions 、 Arithmetic expressions 、 Logical expression 、 Relational expressions, etc , Even a single constant or variable is an expression .

9、 Operator

(1) Arithmetic operator (+、-、*、/、%) devide (/)—— When both divisor and divisor are integers , The result of division is rounded automatically . Find the remainder number (%)—— requirement "%" Both sides of the sign must be integers , It can't be real .

(2) Assignment operator ( = ) Format " Variable = expression ", It means to assign the value of the expression to the storage space corresponding to the variable . Be careful : Assignment number "=" The left side of must be a variable , It can't be a constant or an expression .

(3) Compound assignment operator (+=、-=、*=、/=、%=) It consists of arithmetic operators and assignment operators , It's a combination of two operator functions . for example :a += a + c;

*(4) Self increasing 、 Self - subtracting operator (++、- -) expression When self increasing 、 There is no difference between putting the minus operator before or after a variable when used alone .

for example :++i; Equivalent to i++; Equivalent to i=i+1; Self increasing 、 When the self subtraction operator exists in an expression together with other operators , There's a difference between putting before and after variables .

for example : If defined int i = 3, j; be j = ++i; After statement execution i The value of is 4,j The value of is 4. be j = i++; After statement execution i The value of is 4,j The value of is 3.

(5) Relational operator (>、<、>=、<=、==、!=) Be careful : You can't confuse assignment operators (=) And the equal sign in relational operators (==). The former is to do assignment operation ,

The latter is to judge whether two numbers are equal .

The value of a relational expression is only " Logical truth ( Numerical value 1 Express )" and " Logic false ( Numerical value 0 Express )" Two cases .

If the value of the expression is real , Out of commission "==" perhaps "!=" Judge whether two values are equal or not . (6) Logical operators (!、&&、||)

When calculating logical expressions , When the number involved in the operation " Not 0 Said really "、"0 Said the false "; The solution of the expression "1 Said really "、"0 Said the false ".

Be careful :" Short circuit characteristics " The meaning of . If logic and "&&" The value of the expression on the left side of the operator is 0( false ), The expression to the right of the operator is " A short circuit ", That is, the operation process is omitted by the computer ; If logic or "||" The value of the expression on the left side of the operator is 1( really ), The expression to the right of the operator is " A short circuit ".

(7) An operator (~、^、&、|、<<、>>) Only for character and integer variables . yes C Language is the embodiment of low-level language ability . Be careful : You can't confuse logic with operators "&&" And bitwise and operators "&"; Logical or operator "||" And place

Or operator "|"; Logical nonoperator "!" And bitwise negation operators "~". (8) The comma operator (,)

The function is to calculate the values of expressions separated by commas from left to right , The value of the last expression is the entire comma

Value of expression . Is the lowest priority operator . (9) Conditional operator (? :)

This is a C The only binomial operator in a language , In the form of :< expression 1> ? < expression 2> :< expression 3> (10) The byte operator sizeof

Be careful : You can't confuse byte operators sizeof And string length library functions strlen( ). The former is the operator , The latter is a function .sizeof("Hello") The value of is 6, and strlen("Hello") The return value of is 5.

(11) Priority queue decision for mixed operation of various operators Two 、 Two 、 Two 、 And 、 or 、 Two 、 Tease ! * / % + - > >= < <= == != && || = ,

(12) Casts of data types Format :( Conversion type name ) expression . Be careful : The parentheses around the type name cannot be omitted , The expression depends on the situation. You can add parentheses .

The second part "C Three basic structures of the program " Knowledge point

1、 sentence C There are four types of sentences in language :① Simple sentences ( Divided into expression statements 、 Function call statements );② Empty statement ;③ Compound statement ( One or more statements enclosed by a pair of braces , A compound sentence is grammatically regarded as a sentence );④ Control statement ( Divided into structured statements ,

Such as if sentence 、switch sentence 、while sentence 、do-while sentence 、for sentence ; Unstructured statements , Such as break sentence 、continue sentence 、return sentence 、goto sentence ).

2、 Three basic structures of the program

Sequential structure 、 Selection structure 、 Loop structure

3、 Sequential structure

(1) printf() Use of functions difficulty

The general form is :printf(" Format control string ", List of output items );

among " Format control string " Contains three types of characters —— Ordinary character ( That is, the original output of the characters , Mainly used to do

Prompt information )、 Format specifier ( With "%" start )、 Escape character ( With "/" start ) The list of output items can be omitted , When " Format control string " There is no " Format specifier " when , List of output items

A little ; If yes " Format specifier " when , The list of output items cannot be omitted , And there are several format specifiers , List of output items

There must be several expressions corresponding to the data type , The expressions are separated by commas . The format specifiers you need to master are :%c、%d、%f、%s、%u、%o、%x、%ld、%lf、%e、%%

(2) scanf() Use of functions difficulty The general form is :scanf(" Format control string ", Address list ); among " Format control string " Contains two types of characters —— Ordinary character ( The characters to be input from the keyboard as is , commonly

Play the role of separation and prompt )、 Format specifier ( With "%" start ) Address lists are usually not omitted , according to " Format control string " How many format specifiers are included in , There are just a few addresses in the address list . For ordinary variables , You need to add the address character before the variable name "&", There is no need to add before the array name "&". Be careful 1:scanf() Functional " Format control string " It cannot contain " Escape character ", Otherwise, the input will be invalid . Such as scanf ("%d\n", &a); It's wrong. . Be careful 2:scanf() The normal characters in the format control string are not used for display , It is required to input according to the original model of ordinary characters . Be careful 3:scanf() The second part of the parameter in must be the address list , It can't be an expression . Be careful 4: Mixed input of character and value with no separator between them , Note when to add spaces . for example : Defined

char x; int y; scanf("%c%d", &x, &y); When input from the keyboard , Spaces between characters and integers ; and scanf("%d%c", &y, &x); When input from the keyboard , No spaces between integers and characters .

(3) getchar() Use of functions The function prototype is :char getchar(void); for example :char a; a=getchar( ); This function focuses on the return value of the function .

(4) putchar() Use of functions The function prototype is :char putchar(char); for example :putchar('A'); This function focuses on the parameters of the function .

(5) printf( )、scanf( )、getchar( )、putchar( ) These four functions belong to the standard input and output library functions , When calling, include the header file in the program stdio.h.

(6) For example, it has been defined :char a, b='A'; The following function calls are equivalent

4、 Selection structure

scanf("%c", &a); Equivalent to a = getchar( ); printf("%c", b); Equivalent to putchar(b);

(1) if sentence if There are three forms of statement —— Single branch selection structure 、 Two branch selection structure 、 Multi branch selection structure . Single branch selection structure : if( expression )

Be careful :if Statement expressions are often relational expressions , Don't put "==" The number is misused to "=" Number . explain 1: Parentheses on both sides of an expression cannot be omitted , This expression can be C Any legal expression in language , only

You want the value of the expression to be nonzero ( really ), Execute the following statement body ; otherwise , end if sentence . explain 2: because "if( expression )" and " Statement of body " It's a whole , Grammatically, as a sentence , So in "( surface

Da da )" Can't add after ";", If you add a semicolon , be if The body of a statement becomes an empty statement . explain 3:"if( expression )" Will automatically combine a statement , If there is more than one statement in the statement body , Must use duplicate

In a word , That is, use braces to enclose multiple statements .

Statement of body ;

It's easy to get wrong

It's easy to get wrong

explain 4: To indicate that the body of a statement is subordinate to if, When writing , The body of the statement should be aligned with the keyword if There is an indentation in the position of . Two branch selection structure ( A choice ):

explain 1: Expressions are only written in keywords if Behind , Can not be written in else Behind . explain 2:"if"、" sentence 1"、"else"、" sentence 2" It's a whole , Grammatically, as a sentence , So in

"( expression )" You can't put a semicolon after it , In keywords else You can't put a semicolon after it . explain 3: If " Statement of body 1"、" Statement of body 2" There is more than one statement , You must use a compound statement . explain 4: When writing , The keyword should be if and else alignment ," Statement of body 1" and if There are indentations between ," Statement of body 2"

and else There are indentations between . Multi branch selection structure ( A commonplace ):

explain : The expression must follow the keyword "if" Behind , Can't follow the keyword "else" Behind .

if( expression ) Statement of body 1;

else Statement of body 2;

if( expression 1) Statement of body 1; else if( expression 2) Statement of body 2; … else if( expression n) Statement of body n; else Statement of body n+1;

(2) switch sentence switch( expression ) { case Constant expression 1: sentence 1; <break;> case Constant expression 2: sentence 2; <break;> ……

case Constant expression n: sentence n; <break;> explain 1: keyword switch The value of the following expression must be integer or character , It can't be real . explain 2: keyword case And then " Constant expression ", It can only be a constant or a constant expression , It can't be a variable or a variable

expression . And the value of the expression must be integer or character , Cannot be real and string . Pay attention to when writing

"case" And " Constant expression " There must be a space between ;" Constant expression " Followed by a colon . explain 3: Every case Constant expressions after branches must be different from each other . explain 4: After each branch "break" It can be omitted , If omitted , Then the program continues to the next case Branch

The sentence of , Otherwise, the execution is finished case The branch statement jumps out switch sentence . explain 5: Multiple case Branches can share a set of statements , When a case The statement is omitted after the branch , It means that the branch

Share the statement with the branch immediately after it . explain 6:default It can be omitted . explain 7: When you write, you must pay attention to ①switch The following expressions must be enclosed in parentheses ;② The expression is not followed by parentheses

You can add a semicolon ;③case And the constant expression must be followed by a space ;④ Constant expressions and default It has to be followed by a colon .

5、 Loop structure

There are three elements in the process of programming loop structure —— Initial conditions of the cycle 、 The termination condition of the loop 、 Control the change of the end condition of the cycle .

<default : sentence n+1;> }

while( expression ) The loop body ;

a key

(1) while sentence

while The loop formed by the statement is called the current loop . When the value of the expression is nonzero , Then execute the loop body , Otherwise end the cycle . explain 1: The expression can be C Any legal expression in language , You can't omit the small brackets on both sides when writing

Number . explain 2:"while( expression )" Will automatically combine a statement , If the loop body has more than one statement , You have to use compound

sentence . explain 3:"while( expression )" And " The loop body " It's a whole ,"( expression )" There should be no semicolon after it , Otherwise the cycle

The body becomes an empty statement . (2) do-while sentence do

The loop body ;

do-while A loop formed by a statement is called a until loop . Execute the loop first , Then judge whether the value of the expression is non-zero , Yes, continue with the next cycle , Otherwise end the cycle . explain 1:do It has to be with while A combination of . explain 2: If the loop body has more than one statement , You have to use compound statements . explain 3: The expression can be C Any legal expression in a language , When writing, the brackets on both sides cannot be omitted ,"while( surface

Da da )" The semicolon can't be omitted . (3) for sentence

explain 1: There are three expressions in parentheses , Each expression is separated by a semicolon . All three expressions can default , But it should be supplemented in other corresponding positions .

explain 2:" expression 1" Also known as the initial expression , Once before the whole cycle starts ;" expression 2" Also called termination expressions , Once per cycle before entering , If the value of the expression is nonzero , Then execute the loop body , Otherwise the knot will be

Beam cycle ;" expression 3" Also known as circular expressions , Once at the end of each loop , The initial condition commonly used to control the cycle gradually changes to the termination condition .

explain 3:"for(…)" Will automatically combine a statement , When the loop body has more than one statement , You have to use Compound statement .

(4) break sentence break The function of the statement in the loop body is to end the loop in advance . break The statement appears in switch The function of the sentence is to jump out of this layer switch sentence .

(5) continue sentence continue A statement can only appear in the body of a loop , Its role is to end the cycle ahead of time , Enter the next cycle . When

continue When the statement is executed , Other statements placed after this statement will be skipped . Be careful :continue Statement does not end the whole loop .

6、 Commonly used algorithm 、 Common library functions

(1) Exchange the values stored in two variables —— Use three statements that end with the beginning . for example : Defined int a=3, b=4, t; To exchange a and b The value in , Use the following three statements t = a; a = b; b = t;

(2) Mathematical functions ( Need to include header file math.h)——sqrt( )、fabs( )、pow( )、exp( ) (3) Fiboracci series (4) The prime question (5) N The problem of summation of terms (6) Iterative method

while( expression );

for( expression 1; expression 2; expression 3) The loop body ;

a key , difficulty

difficulty a key , difficulty

The third part " Array 、 character string " Knowledge point

1、 One dimensional array (1) The definition form of one-dimensional array : Type specifier Array name [ Constant expression ]; Be careful : In square brackets " Constant expression " Represents the number of elements in the array . It can only be constant , It can't be a variable or a variable expression . explain 1: Once an array is defined , Just allocate several storage units in the memory space , The size of each storage unit is determined by the number of

Depending on the type . For example, there is the following definition :int a[10]; Then the computer is an array a Continuous distribution 10 Storage unit , Every The storage unit occupies 4 Bytes , The total is 40 Bytes of storage space .

explain 2: Once an array is defined , The array name represents the first address of a continuous storage space , Array names are constants , Always point to that number The memory unit address of the first element of the group .

(2) A reference to one-dimensional array elements : Array name [ Subscript ] As with general variables , Array must be defined first , After use . A reference to an array element refers to the use of a specified element in a defined array ,

adopt " Subscript " To specify the element to be referenced . Be careful 1: The lower bound of the subscript must be "0", The upper limit is determined by the value of the constant expression when the array is defined , by " Constant expression value -1".

Suppose we have the following definition :int a[10]; Then the subscript range that references the array element is "0~9", If the subscript exceeds this range , It's called array out of bounds , Will cause the program to run wrong .

Be careful 2: You must distinguish between... In square brackets when defining an array " Constant expression " And array elements " Subscript ", They have different meanings and functions . The former indicates the size of the array , The latter indicates which element in the array to refer to .

(3) Initialization of one dimensional array As with general variables , After the array definition , If you don't give it an initial value , Then the initial value in the array element is a random number . Assign... To an array element

There are usually two ways to value : One is initialization ; One is to use a loop structure to assign values to each array element in turn . Array initialization methods are divided into :① All elements are given initial values ;② Some elements are given initial values ;③ When all elements are given initial values, no number can be specified

Group length . (4) One dimensional array element input 、 Output Because the elements in the array are several values of the same type , It cannot be input or output as a whole , It has to be for a single element

Make input or output , This is where the loop structure is used , For a one-dimensional array , Using a single-layer loop .

2、 Two dimensional array

(1) The definition form of two-dimensional array : Type specifier Array name [ Constant expression 1][ Constant expression 2]; explain 1:" Constant expression 1" Indicates the number of rows in a two-dimensional array ," Constant expression 2" Indicates the number of columns in a two-dimensional array . explain 2: A two-dimensional array can be regarded as a special one-dimensional array , Two dimensional array elements in memory are " By line ". (2) Two dimensional array element reference : Array name [ Line subscript ][ Column subscript ]

explain : Like a one-dimensional array , The row subscript and column subscript of two-dimensional array element reference can't be out of bounds . Suppose we have the following definition :int a[3][4]; When the array element is referenced , The range of line subscripts is "0~2", The range of column subscripts is "0~3".

(3) Initialization of 2D array There are four ways to initialize a two-dimensional array :① All elements are initialized ( Use two layers of curly braces );② Branch part of the element initial

turn ;③ According to the numerical storage order, do not initialize ( Use a layer of curly braces );④ According to the numerical storage order, do not initialize , When it comes to the whole

When an initial value is assigned to a part element , You can omit constant values that determine the number of rows . (4) Two dimensional array element input 、 Output Use double loop nesting to input all elements of a two-dimensional array 、 Output .

3、 Character arrays and strings

(1) The relationship between character array and string A character array is a collection of character data . It is defined as :char Array name [ Constant expression ]; Like other types of arrays , take

Each character in an array is treated as an individual . When these characters have '\0' when , You can think of them as a whole , String character . Strings have constants , But there are no string variables , String constants are stored in character arrays , The premise is the large size of the character array

Small enough to hold the entire string , Include the terminator of the string '\0'. (2) Initialization of character array When all the characters stored in the character array are regarded as independent individuals , Its initialization method is the same as other types of arrays . When the character array

When a string is stored , The initialization methods are as follows : ① char a[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; ② char a[6] = {"Hello"}; ③ char a[6] = "Hello"; ④ char a[] = "Hello"; (3) A way to store a string in a character array After defining the character array , If you want to store a string in an array , In addition to the initialization methods mentioned above , There are also the following methods , Be careful

You cannot use the method of an assignment statement . Suppose there's a definition :char a[50]; Method 1:scanf("%s", a); Be careful :a Represents the first address of the array , There's no address before it &. Method 2:gets("%s", a); Method 3: int i=0;

while((a[i] = getchar()) != '\n') i++; a[i] = '\0';

a key Be careful : You can't use the method of assignment statement to store string into character array . The following is wrong , The reason is that the array name is constant , Always point to the first address of the array , When writing string constants , The system gives the first name of a nameless storage area it occupies in memory Address , It is not allowed to reassign the constant array name to another address space .

char a[50]; a = "Hello"; ( error ) (4)'\0' When the system automatically adds 、 When do I need to add it manually The end flag of a string constant is '\0', Lack of '\0', Cannot be called a string constant . The following is a list of when the system will automatically add '\0',

When the programmer needs to add it manually '\0' Several situations of . Automatically added by the system :( Suppose there is a definition : char a[50];) call scanf Function to enter a string from the keyboard . for example :scanf("%s", a); call gets Function to enter a string from the keyboard . for example :gets(a); When initializing a character array as a string constant . for example :char a[50] = "Hello"; call strcpy Function to copy a string into a character array . for example :strcpy(a, "Hello");

Need to add... Manually '\0' The situation of : When initializing a character array as a character . for example :char a[ ] = {'H', 'e', 'l', 'l', 'o', '\0'}; First define the character array , When assigning a single character to each array element . for example :char a[50];

a[0]='H'; a[1]='e'; a[2]='l'; a[3]='l'; a[4]='l'; a[5]='\0'; The original string stored in the character array is processed , Destroyed the original string of '\0', You need to add the new string manually '\0'

(5) String input 、 Output The first method : call scanf、printf Function implementation , The format specifier uses "%s". for example :

char a[50]; scanf("%s", a); // When a space or carriage return is encountered, the system considers the string input to be over printf("%s", a); // String output

The second method : call gets、puts Function implementation . for example : char a[50]; gets(a); // When a carriage return is encountered, the system considers the string input to be over

puts(a); explain :scanf and gets The difference when you enter a string is ——scanf Do not accept spaces , This function takes the space as the end of the string input

sign . and gets Receives a space as a valid character in a string , This function only considers carriage return as the end of string input flag . (6) String handling functions Find string length function :strlen(s)

for example :char s[50]; int len; len = strlen(s); explain 1: Use strlen When calculating the length of a string , The calculation is the first '\0' Number of valid characters before , Function return value does not include

enclosed '\0' Number of bytes occupied . explain 2: Pay attention to distinguish between strlen and sizeof. First ,strlen It's a library function , and sizeof It's the operator ; secondly ,strlen meter

It is the number of bytes occupied by the valid characters of the string , barring '\0' Occupied space , and sizeof It's the character that counts The number of bytes an array or string occupies in memory , Include '\0' Occupied space . for example :

char s[20]="Hello"; int x, y, m, n; x = strlen(s); y = sizeof(s); m = strlen("Hello"); n = sizeof("Hello"); In the above examples , Variable x and m The values are all 5, because strlen Function only counts the number of valid characters in a string The number of bytes used . Variable y The value of is 20, because sizeof(s) It's an array a The number of bytes used in memory . Variable n The value of is 6, because sizeof("Hello") It's a string "Hello" The number of bytes used in memory , Include '\0' Occupied space .

String concatenation function :strcat(s1, s2) for example :char s1[50] = "Hello", s2[50] = " every one";

strcat(s1, s2); // Represents a string " every one" Paste to string "Hello" Behind strcpy(s1, "every one");

String comparison function :strcmp(s1, s2) explain : This function takes out the corresponding characters of two strings in turn from left to right for comparison , Compared to the corresponding characters ASCII code

Value size . When string s1 Greater than string s2 when , The function returns 1; When string s1 be equal to s2 when , Function returns to return 0; When string s1 Less than s2 when , The function returns -1.

String copy function :strcpy(s1, s2) explain : This function will s2 Copy the string to s1 Point to the storage space of , requirement s1 The storage space pointed to must be enough

Big , Can hold the string to be copied . for example : char s1[50], s2[50] = "Hello";

strcpy(s1, s2); // Represents an array of characters s2 Copy the string stored in to the character array s1 in strcpy(a, "China"); // Represents a string "China" Copy to character array a in

4、 Commonly used algorithm

(1) Bubble sort (2) Sorting by selection

a key

a key

The fourth part " function " Knowledge point

1、 Library functions and custom functions

(1) Library function : At present, the library functions we have learned include standard input and output class library functions 、 Math class library functions , When a library function is invoked in a program , Must contain the corresponding header file . For example, the header file corresponding to the standard input / output class library function is <stdio.h>, Math class library

The header file corresponding to the function is <math.h>. (2) User defined functions : Functions written by users to complete specific functions , Also known as a subfunction . (3) One C The program consists of a main Function and several sub functions .

2、 Function definition 、 Function call 、 The concept of function declaration

(1) Function definition —— That is to define the function function . Undefined functions cannot be used . (2) Function call —— That is, to execute a function , When you call a function , The program jumps to the first sentence of the called function and starts execution , perform

To the last sentence of the called function , Then the program returns to where it called the function . (3) Function description —— That is to inform the compiler that the function has been defined .

3、 The format of the function definition

< Function type > Function name (< Parameter table >) {

a key Function head

< Function body statement > } A function consists of a function head and a function body , The first part of the function is determined by the function type 、 Function name 、 The parameter table consists of . Description of function types explain 1: Function types are divided into " Empty type ( Keywords are void)" and " Non empty type ( You need to specify a specific return type , Such as int、

float、double、char、 Pointer types 、 Structure type, etc )". explain 2: When default " Function type " when , The default function return type is int type . explain 3: When the function type is " Non empty type " when , There must be... In the body of a function return sentence , It's written in "return( expression );",

The type of the expression value must be the same as the function type , Otherwise, the compiler will give a warning . explain 4: When the function type is "void" when , You don't need to return sentence , Or just write "return ;" that will do . explain 5: The function type is C Keywords in language , stay VC++6.0 It's blue in the compile environment . Description of function name explain 1: Function names must match C Naming rules for language identifiers . The best way to name a function is by name . explain 2: The same name is not allowed for each defined function in the same program . A description of the parameter table

explain 1: In this case, the parameters in the parameter table are called formal parameters , abbreviation " Shape parameter ". Formal parameters must be enclosed in a pair of parentheses . explain 2: If there are no parameters in the parameter table , It's called a nonparametric function , At this point, you can write keywords in parentheses void, Or everything

Don't write . explain 3: If there are parameters in the parameter table , It's called a parametric function , In this case, the data type of each parameter must be explicitly stated in the brackets .

Be careful : Each parameter must have its own type specifier , Such as int fun(int a, int b, char c) A description of the body of a function

explain 1: The body of the function must be enclosed in a pair of braces , Before the function body is the explanation part , The following is the execution section . explain 2: The head and body of a function are a whole , Can't be separated . for example , Enclose the parentheses in the parameter table and the functions

It's wrong to put a semicolon between the braces of a body .

4、 Function call

A function that has been defined , It can only be executed when a function call occurs . The process of function calling is that the program jumps to the called function

The first sentence of the number begins to execute , Execute to the last sentence of the called function , Then the program returns to the function call statement . The general form of a function call : (1) The calling form of function with parameters : Function name ( Parameters ) (2) The calling form of parameterless function : Function name ( )

Function call by value The parameters of a function call are called actual parameters , abbreviation " Actual parameters ". When a function call occurs , Arguments pass values to formal parameters ,

Realize the value transfer of function call . In order to ensure the correct value transfer when the function is called ," Actual parameters " And " Shape parameter " There should be strict correspondence , It can be summed up as "3

A consensus and 1 There's a discrepancy "—— Regulations : The number of arguments 、 type 、 The order must be the same as the number of formal parameters of the called function 、 type 、 In the same order . The parameter names of the actual participating parameters can be different . C There are three ways to call functions in language

(1) As a separate statement . for example :printf("Hello world!"); (2) As part of the expression . for example :y = sqrt(9); (3) As arguments to other functions . for example :printf("y = %lf\n", sqrt(9));

5、 Function declaration

edit C The program , If the function definition is written after the function call , You need to make a function declaration , Otherwise, you can omit the function declaration . The general form of a function declaration is :

Type name Function name ( type 1, type 2,… , type n); explain : Function declaration 、 Function definition 、 There must be a strict correspondence among function calls , The function types of the three should be consistent , Function name

Need to be the same , Number of parameters 、 type 、 The sequence needs to be consistent .

6、 Nested calls to functions

C Nested function definition is not allowed in language . So the sum of the functions is

They are parallel , There is no problem of upper level function and lower level function . however C The language allows the definition of one function to have a pair of functions in the definition of another

The number of calls . So there are nested calls to functions . That is, in the transferred letter

Other functions are called in the number . The relationship is shown in the figure : In execution main The process of function is called

f1 function , So I went to execute f1 function , In execution f1 Function and call f2 function , So I went to execute f2 function ,f2 The function returns... After execution f1 The breakpoint of the function continues ,f1 The function returns... After execution main The breakpoint of the function continues .

7、 The scope and storage category of the variable ( The teaching material 12.1~12.3 section )

The scope of variables refers to the classification of the scope of variables in space , It is divided into global variables and local variables . Where the global variables are

Wide range of action , The scope of local variables is narrow . The storage category of variables refers to the classification of the existence time of variables in terms of time , Divided into dynamic variables 、 Static variables . The dynamic

Variables exist for a short time , Static variables exist for a long time .

(1) Scope of variable The scope of a variable is the scope of the variable , It is divided into global variables and local variables , The local variables are divided into the local variables of the function body in order to

And local variables of compound statements .

Global variables Local variables in a function Local variables in compound statements Define the location Defined outside the body of the function Defined inside the body of the function Defined inside a compound statement

Scope From defining the position to the whole .c The end of the file is valid

This function is valid in vivo This compound sentence is valid

matters needing attention (1) The same .c Global variables in a file cannot have the same name

(1) Must be written before executing the statement (2) Local variation in the same function

(1) Must be written before executing the statement (2) A bureau in the same compound statement

a key

(2) Global variables are allowed to have the same name as local variables , When you have two names , local variable

Mask global variables

Quantity cannot be renamed (3) When it has the same name as a global variable , Local variables mask global variables

Part variables cannot have the same name (3) Compared with the first two variables , This is the smallest variable in scope

explain 1: From this table we can see that , The widest scope is global variables , The second is the local variables in the function body , The narrowest range is the local variable in the compound statement .

explain 2: When the global variable 、 When a local variable has a duplicate name , A narrow range variable will automatically mask a wide range variable . explain 3: Variables and formal parameters defined in a function body are local variables . (2) Storage category of variables The storage categories of variables are divided into auto( Dynamic )、static( Static type )、register( Register type )、extern( External type ). Dynamic variables —— Only in a certain period of time . For example, the formal parameters of a function 、 Local dynamic variables in a function , This kind of change

When a function call occurs , The system temporarily allocates storage space for them , But as the function call ends , The storage space of these variables is freed up , The value of the variable disappears . Dynamic variables are divided into global dynamic variables 、 Local dynamic variables .

Static variables —— The lifetime is the whole execution process of the program , Until the end of the program . Once this kind of variable is defined , The system is Allocate storage space for it , Static variables occupy these storage spaces in the whole process of program running , So it's also called permanent storage .

Static variables are divided into global static variables 、 Local static variable . Be careful : If there is no initial value after the static variable is defined , Then the initial value is zero . This is different from dynamic variables , If there is no initial value after the definition of dynamic variable , Then the initial value is a random number .

Register variables —— A variable that is used more frequently can be defined as register type , To improve the speed of the program . Deposit Device variables are dynamic variables , Storage space is automatically released at a specific time . Be careful : Register variables are integer only 、 Character 、 Pointer type .

External variables —— If in a source file ( for example a.c) A global dynamic variable is defined in int x, In another source

auto

static

register

extern

a key

a key

file ( for example b.c) You need to refer to this global variable in x, It's in "b.c" Of variables in x It's as follows bright "extern int a;" after , You can quote "a.c" Variables defined in x. Be careful : Global variables can only be defined once , But use extern It can be explained many times . This is similar to the function , Function definition can only be one time , And the function description can be multiple times .

8、 Storage classification of functions ( The teaching material 12.4 section )

(1) use static Explain the function After a function is defined , In addition to being called by the source file , Not allowed to be called by other source files , Then the return value at the beginning of the function

Type is preceded by static Keyword can achieve the above purpose . The advantage of this is to avoid different .c The file defines a function with the same name, causing confusion .

(2) use extern Explain the function After a function is defined , In addition to being called by the source file , It can also be called by other source files , Other source files are calling the function

A few years ago , You need to use extern Key words , You can then call .

9、 Compile preprocessing ( The teaching material 13.1 section )

stay C In language , All with "#" The first line is called the compile preprocess command line , Requirements "#define" and "#include". Be careful : You can't add... At the end of each line ";" Number .

(1) Macro replace —— #define Macro definition without parameters

#define Macro name replace text Instructions : The replacement text can contain macro names that have already been defined Write instructions : When macro definitions are written in multiline , Add a backslash at the end of the line "\"; Macro names are usually capitalized ; Macro definitions are usually written at the beginning of a program . Macro definition with parameters

#define Macro name ( Parameter table ) replace text Instructions 1: There are only parameter names in the parameter table , There is no type description . Instructions 2: If there are parentheses in the replacement text , The macro replacement must have parentheses ; conversely , If you replace

There are no parentheses in the file itself , You can't add parentheses when you replace a macro . Write instructions : Macro name and parentheses must be next to ; Brackets cannot be omitted ;

a key

(2) File contains —— #include The so-called file inclusion means to include all the contents of another file in one file ,#include The form of the command line is as follows : #include " file name " perhaps #include < file name > If the file name is enclosed in double quotation marks , It means that the system first searches the specified containing file in the directory where the source program is located , If you can't find it , Again

Go to the relevant directory according to the standard way specified by the system . If the file name is enclosed in angle brackets , The system will directly search the relevant directory according to the standard way specified by the system .

The fifth part " The pointer " Knowledge point

1、 The basic concept of pointer ( The teaching material 8.1 section ) (1) The memory space of a computer is made up of many storage units , Each storage unit represents a byte of capacity , Every storage order

Every yuan has a unique number , The address . The variables used in the process of program running are stored in these storage units . The values of variables are

The two methods , One is to use the variable name to access its content , be called " direct method ", The other is to use the address of variable to update its content

Row access , be called " indirect method ". (2) The pointer ── The address . The address of a variable is called the pointer to the variable , You can find the variable through its pointer . Pointer to the variable ── Variables dedicated to storing the addresses of other variables . The difference between pointers and pointer variables , It's the area between variable value and variable name

other . Be careful : Pointer variables store address values , Instead of the usual numerical value .

2、 The definition of a pointer variable 、 assignment ( The teaching material 8.2 section )

(1) The definition of a pointer variable : Type identifier * Pointer variable name ; explain 1: The type identifier here is called... Of a pointer variable " Base type ", That is to say, which type of variable should be stored in the pointer variable

site , The base type of a pointer variable must be of the same type as the normal variable it points to , Otherwise, the program will run wrong . explain 2: Compared with the definition of ordinary variables , Except for an asterisk in front of the variable name "*" Outside , The rest are the same . Be careful : The asterisk at this time

Just an identifier , The variable after the identifier is the pointer variable , Instead of ordinary variables . explain 3: For example, there is a definition "int *p;" Representation defines a int Pointer variable of type p, At this point, the pointer variable does not point to a

Specific variables ( Say the pointer is suspended ). Using dangling pointers can easily damage the system , Cause system paralysis . a key

Key points and difficulties

explain 4: No matter what type of pointer variable it is , stay VC++6.0 All pointer variables defined in the compilation environment occupy 4 Bytes of storage space , It's used to store the address . This is not the same as ordinary variables , Common variables depend on different data types , It takes up

There is a difference in the number of bytes of storage space . (2) Assignment of pointer variables Same as ordinary variables , Pointer variables can be assigned values when they are defined , Called initialization ; You can also define , Then use the assignment statement to

Its assignment , The assignment method is : Pointer variable name = Some address ; There are several ways to assign values to pointer variables :

Method 1 : Pointer variable name = & Common variable names Method 2 : Pointer variable name = Another pointer variable of the same type and assigned value Method 3 : The third is to call library functions malloc perhaps calloc, Call after the pointer is used free Release it . for example : int *p; // The following two writing methods can be implemented as pointer variables p Dynamic allocation 40 The function of one byte storage space p = (int *)malloc(10 * sizeof(int)); Equivalent to p = (int *)calloc(10, sizeof(int));

3、 Pointer arithmetic ( The teaching material 8.4.2、8.4.3 section )

(1) Two important operators in pointer operation * ( Take the content symbol ): Take out the contents of the following memory unit . &( Fetch address ): Get the memory unit address of the subsequent variable . explain : The content symbol here is also an asterisk , In appearance, it is the same as the identifier when the pointer variable is defined , But the meaning of both ends

Not all the same , The former is the operator , The latter is just an identifier . (2) Move the pointer

a key

a key

To move a pointer is to add or subtract an integer from a pointer variable , Or by assignment , Make a pointer variable point to an adjacent storage location .

Only if the pointer points to a continuous string of storage units ( For example, an array of 、 character string ) when , The movement of the pointer makes sense . The pointer moves through arithmetic operations ( Add 、 reduce ) To achieve , The number of bytes that the pointer moves is closely related to the basic type of the pointer . For example, it has been decided

The righteous :char *p1; int *p2; Do the following operation "p1++; p2++;" after , The pointer p1 The address value stored in is added by one unit , The pointer p2 The address value stored in is increased automatically 4 A unit .

(3) Comparison operations The comparison operation is to compare the size of the address values stored in two pointer variables . (4) Mixed operation of pointers For example, there is a definition :int a, *p; The following examples of hybrid operations need to be carefully considered .

difficulty

①"&*p" What is the meaning of ?②"*&a" What does it mean ?③"(*p)++" What does it mean ?④"*p++" What does it mean ?⑤"*++p" What does it mean ?⑥ "++*p" What does it mean ?

4、 Transfer of address values between functions ( The teaching material 8.5 section )

(1) The argument passes the address value to the formal parameter If the formal parameter of a function is a pointer variable , The corresponding argument must be an address value of the same base type or a pointer to a storage unit

Needle variables . The teaching material 7.5 The content of this section is " The transfer of values between functions ", In this way, it completes the one-way transfer from real parameter to formal parameter , namely

When a function call occurs , An argument passes its value to a formal parameter , After the function is called , The change of formal parameter does not affect the value of corresponding actual parameter ,

So this numerical transfer is called " A one-way " Of . And the content of this section is " Transfer of address values between functions ", It is characterized by the address of a memory unit in the main calling function , In being

In the calling function, you can modify the value of the memory unit in the main calling function through formal parameters , This makes it possible to change the corresponding parameter values through formal parameters

It's possible , So by passing address values , The data transfer between the main function and the called function can be realized " two-way " The transfer . " Address " Another advantage of this way is that : Multiple data can be returned from the called function to the main function . this

Not at all " Pass value " It can't be done in this way , In the way of value transfer, the called function can only use return Statement returns a data to the calling function . Students need to carefully distinguish between functions " Pass value " And " Address " The characteristics of these two ways are different , When making questions, pay attention to the analysis of when to pass the value

The way , When is the mode of address delivery . (2) adopt return Statement returns the address value When the type of function return value is pointer type , Instead of a normal data type , Indicates that the called function returns to the main calling function after calling

It's an address value , Instead of a normal number . Attention should be paid to return The expression value of the statement should be a pointer type ( Address values ).

a key

a key

5、 One dimensional arrays and pointers ( The teaching material 9.2 section )

(1) The array name is an address constant (2) Using pointers to access array elements is based on the feature that array elements are stored in order .

Mode one : Using the first address of the array ( Array name ) Accessing array elements . Be careful : Because the array name is constant , So logarithm Group names cannot be incremented , You have to use a variable i To achieve sequential access to array elements .

for example : int a[10], i = 0; while(i < 10) scanf("%d", &a[i++]); perhaps while(i < 10) scanf("%d", a+ i++); Mode two : Using pointer variables to access array elements . for example : int a[10], i = 0, *p = a; while(i < 10) scanf("%d", p++);

(3) Two equivalent methods of referencing one-dimensional array elements —— The subscript method 、 Pointer to the method Suppose we have the following definition :int a[3], *p = a; It can be concluded from the table above that , The subscript method takes the expression of array element value as "a[i]" or "p[i]", Pointer method to get the value of array elements

The method to "*(a+i)" or "*(p+i)". The subscript method takes the expression of array element address as "&a[i]" or "&p[i]", The pointer method to get the address of an array element is "a+i" or "p+i".

(4) Suppose there is a definition :int a[10], *p = a; be p and a The same thing is : It's all pointers , The first address of the array . The difference is :a Is the address constant ,p It's a pointer variable .a Always point to the first address of the array , Until the array

The storage space of is reclaimed by the system ;p It's a variable. , It can be reassigned to point to other storage space .

6、 One dimensional array and function parameters ( The teaching material 9.3 section )

(1) Array elements as function arguments Because array elements are equivalent to independent ordinary variables , When array elements are used as function arguments , What we achieve is " Pass value " The way , That is, one-way transmission . Only the values of array elements can be used in the called function , You cannot change the initial value of an array element . (2) The address of an array element as a function argument

When the address of an array element is used as a function argument , What we achieve is " Address " The way , It can achieve the function of two-way data transmission . That is, in the called function , Not only can we use formal parameters to use the initial values of the array elements , You can also modify the initial value of the array element

Purpose . (3) Array names as function arguments

When array names are used as function arguments , Because the array name itself is an address value , So what's achieved is " Address " The way , It can achieve the function of two-way data transmission , The corresponding parameter must be a pointer variable of the same type as the array . In the called function ,

You can use formal parameters ( Pointer to the variable ) Use all the elements in the array , You can also modify the initial values of these elements . explain 1: When array names are used as function arguments , The corresponding formal parameters can be written in the following ways , Both represent a reference that is consistent with the array type

Needle variables . void fun(int a[10]) perhaps void fun(int a[ ]) perhaps void fun(int *a) { … } { … } { … }

explain 2: When the array name is used as an argument , The corresponding parameter is a pointer variable of the same type as the array , When a function call occurs , system It's just a pointer variable ( Shape parameter ) Distribute 4 Bytes of storage space , It's not that the allocation is the same as the entire array Storage capacity occupied . for example :

a[0] a[1] a[2] The subscript method

p[0] p[1] p[2] *a *(a+1) *(a+2)

Count

Component

Primeval

The number Pointer to the method

*p *(p+1) *(p+2)

&a[0] &a[1] &a[2]

The subscript method &p[0] &p[1] &p[2]

a a+1 a+2

Count

Component

Primeval

Address pointer method

p p+1 p+2

a key

a key

void main(void) void fun(int a[10]){ { int a[10]; … … printf("%d", sizeof(a)); printf("%d", sizeof(a)); …

fun(a); } …

notes :fun The print result in the function is "4", Because the parameter is a pointer variable , Any type of pointer variable , The system allocates 4 Bytes of storage space .

}

notes : The print result in the main function is "40", because a After the array definition , The system assigns it 40 Bytes of storage space .

7、 Two dimensional arrays and pointers ( The teaching material 9.6 section ) difficulty

(1) Two dimensional array " Base type " The understanding of the Assumption defined :int a[3][4], *p;

Like a one-dimensional array , The two-dimensional array name is also an address constant . A two-dimensional array can be regarded as composed of multiple one-dimensional arrays , According to the above definition , Two dimensional array a It's made up of three one-dimensional arrays , Every time

There are four elements in a one-dimensional array ,a[0]、a[1]、a[2] They are the array names of these three one-dimensional arrays , Each of them represents the first address of the three one-dimensional arrays , It's also an immutable constant address .

Based on the above analysis , It can be understood in this way :① 2D array name a The base type of is 4 individual int type ;② One dimensional array name a[0]、a[1]、a[2] The base type of is 1 individual int type ( That is, the type of array elements ). Assumption defined :int a[3][4]={1, 2, 3, 4, 5, 6, 7, 8, 9 10, 11, 12}; The following diagram shows a two-dimensional array name 、 One dimensional array name 、 The correspondence between the elements in a two-dimensional array .

On the right side of the above diagram is a two-dimensional array 12 Elements , Each element takes up one int Type of storage space (4 Bytes ),

Suppose the first element in the first line a[0][0] The address for 0x1000, Analysis shows that the first element in the second line a[1][0] The address for 0x1010, The third line, the first element a[2][0] The address for 0x1020, The first addresses of the three elements are given by a[0]、a[1]、a[2] To hold the . In the middle of the diagram is a[0]、a[1]、a[2] A one-dimensional array of , These three elements are primary pointers , It stores the address value ( Namely 0x1000、0x1010、0x1020). On the left side of the diagram are two-dimensional array names a, It's a secondary pointer , Store by a[0]、a[1]、a[2] The first address of a one-dimensional array of three elements ( The assumption is 0x1030).

It can be seen from the above analysis ,"a[i]" Is the first level pointer , The base type is 1 individual int type ."a" It's a secondary pointer , The base type is 4 individual int type . for example :"a[0]" Point to elements a[0][0], be "a[0]+1" Indicates that the address moves backward , Point to elements a[0][1], That is, one level pointer plus 1 Indicates that the address moves backward 1 individual int type ."a" Point to elements a[0], be "a+1" Indicates that the address moves backward , Point to elements a[1], That is, the secondary pointer plus 1 Indicates that the address moves backward 4 individual int type .

(2) The first address of each element in a two-dimensional array a( perhaps a[0]) Represents the first address of the first element in a two-dimensional array ;a+1( perhaps a[1]) Represents the first address of the element in the second line ;

a+2( perhaps a[2]) Represents the first address of the third line element .

1030 a

1000

1010

1020

a[0]

a[1]

a[2]

The first address of the line is 1000 1 2 3 4

5 6 7 8

9 10 11 12

a[0][0] a[0][1] a[0][2] a[0][3]

a[2][0] a[2][1] a[2][2] a[2][3]

The first address of the line is 1010

The first address of the line is 1020

The first address of the one-dimensional array is 1030

2D array name a ( The secondary pointer )

One dimensional array name a[i]( First level pointer )

Two dimensional array elements a[i][j] ( Content )

(3) The address of each element of a two-dimensional array In a two-dimensional array i Xing di j An element of a column a[i][j] The address of can be obtained by the following expressions : ①&a[i][j] ②a[i]+j ③*(a+i)+j ④&(*(a+i)[j]) ⑤a[0]+4*i+j ⑥&a[0][0]+4*i+j

(4) Referencing elements of a two-dimensional array by address Reference two-dimensional array number i Xing di j Several expressions for the elements of a column are as follows : ①a[i][j] ②*(a[i]+j) ③*(*(a+i)+j) ④*(a+i)[j] ⑤*(a[0]+4*i+j) ⑥*(&a[0][0]+4*i+j)

(5) Reference two-dimensional array elements by creating a pointer array Assumption defined :int *p[3]; Will p Called an array of pointers . because "[ ]" Has a higher priority than "*" The priority of the , therefore p First and foremost "[ ]" combination , constitute p[3], The explanation is a number Group ,"p[3]" And again "int *" combination , The data type representing each element in the array is " Integer pointer " type , So we will "int *p[3]" Called an array of pointers —— That is, it's an array first , Each element in the array is a pointer type . Let's analyze " Pointer array " And " Two dimensional array " Correspondence of , Assumption defined :int *p[3], a[3][2]; ( notes In the above definition , The number of elements of the pointer array must be consistent with the line number constant of the two-dimensional array , namely p[3] Medium "3" And a[3][2] Medium "3" Be consistent ). The following expression means that p Each element in the array ( Pointer to the variable ) Point to a Every... In the array That's ok .( See the textbook P128 chart 9.6) The first method :p = a; The second method :for(i = 0; i < 3; i++) p[i] = a[i]; At this time , You can use the pointer array p To refer to a two-dimensional array a The elements in .

① p[i][j] Equivalent a[i][j] ② *(p[i]+j) Equivalent *(a[i]+j) ③ *(*(p+i)+j) Equivalent *(*(a+i)+j) ④ *(p+i)[j] Equivalent *(a+i)[j]

(6) Reference two-dimensional array elements by creating a row pointer Assumption defined :int (*q)[2]; Will q It's called a row pointer . Students need to carefully distinguish the pointer and pointer array . Because of the parentheses in the definition , therefore q First and foremost "*" combination , explain q Is a pointer variable , And then with "[3]" junction close , Explain pointer variables q The base type of is an array of two integer elements . Let's analyze " That's ok " And " Two dimensional array " Correspondence of , Assumption defined :int (*q)[2], a[3][2]; ( Pay attention to In the upper definition , The number of elements of row pointer must be consistent with the column number constant of two-dimensional array , namely (*q)[2] Medium "2" And a[3][2] Medium "2" Be consistent ). Then the pointer variable q The base type of is related to a The base types of are the same ,q = a; Is a legal assignment statement , Express The pointer q Points to a two-dimensional array a The first address , In this case, you can use the line pointer q To refer to a two-dimensional array a The elements in .

① q[i][j] Equivalent a[i][j] ② *(q[i]+j) Equivalent *(a[i]+j) ③ *(*(q+i)+j) Equivalent *(*(a+i)+j) ④ *(*(q+i)[j]) Equivalent *(*(a+i)[j])

(7) Two dimensional array 、 Pointer array 、 The correspondence between row pointers Assumption defined :int a[3][2], *p1[3], (*p2)[2]; be a It's a two-dimensional array name 、p1 Is the pointer array name ,p2 Is the row pointer name , Because the number of rows in a two-dimensional array is the same as the dimension of a pointer array , The number of columns in a two-dimensional array is the same as the dimension of a row pointer , So they're three

It can produce corresponding relationship . The following statement is legal p1 = a; p2 = a; Can be a、p1、p2 Both are considered secondary pointers .

difficulty 8、 Two dimensional array names and pointer array names as function arguments ( The teaching material 9.7 section )

(1) Two dimensional array names as function arguments First of all, remember when one-dimensional array names are used as function arguments , The corresponding formal parameter is a pointer variable of the same type as the array element , There are several ways to write formal parameters :

main() { int a[3]; … fun(a); // One dimensional array names as function arguments … }

be fun The first part of a function can be written in the following ways :(1)void fun(int

p[3])

p[ ]) *p)

(2)void fun(int (3)void fun(int

When a two-dimensional array name is used as a function argument , The corresponding formal parameter must be a row pointer variable , Formal parameters can be written in the following forms :

main() be fun The first part of a function can be written in the following ways : { int a[2][3]; (1)void fun(int p[2][3])

(2)void fun(int p[ ][3])

… fun(a); // One dimensional array names as function arguments

… (3)void fun(int (*p)[3]) } Pay attention to the above , Column subscript cannot be default . Either way , The system puts p Processing into a row pointer .

(2) Pointer array names as function arguments When an array of pointers is used as an argument to a function , The corresponding parameter should be a pointer to a pointer . Formal parameters can be written in the following forms :

main() be fun The first part of a function can be written in the following ways :{

(1)void fun(int *p[3]) (2)void fun(int *p[ ])

int a[2][3], *p[3] = a; … fun( p ); // Pointer array names as function arguments … }

It is similar to the formal parameter when one-dimensional array name is used as real parameter ( When one-dimensional array name is used as an actual parameter, the corresponding formal parameter can be written in three ways ), When the pointer array

As an argument to a function , Still passing a one-dimensional array name , There are also three ways to write the corresponding formal parameters , It's just that the type of the parameter is a pointer class

It's just type .

9、 Strings and pointers ( The teaching material 10.2 section )

(3)void fun(int **p)

a key

(1) Make the pointer point to a string Because each character in the string is stored in the memory space in order , So it's convenient to use pointers to manipulate strings . With

Here are several ways to point a character pointer variable to a string : Method 1 : When defining a character pointer variable, assign a string to its initial value ( initialization ). for example : char *p = "Hello"; Method 2 : First define the character pointer variable , Then the pointer variable points to the string through the assignment statement . for example : char *p; p = "Hello"; The string constant in the example "Hello" Given in the program is its first address in memory space , So you can assign values

Statement to assign the first address of this anonymous storage area to the pointer variable , Make the pointer point to the string . Method 3 : First define the character pointer variable , Then assign the pointer variable to a valid address value ( You can assign a pointer to a character

The first address of the array , Or call malloc Function dynamically allocates a storage space for a pointer variable ), Last call strcpy Function copies the string into the memory space pointed to by the pointer . for example :

char *p; p = (char *)malloc(6 * sizeof(char));

strcpy(p, "Hello");

char a[6], *p; p = a; strcpy(p, "Hello");

perhaps

Be careful : Calling strcpy Function before , The pointer p Must have pointed to a valid storage space , And then we can go to this

The string constant is stored in the storage space . If the pointer is just a definition , There is no valid address value assigned to it , In this way The pointer can't be used .

(2) Some mistakes are easy to make A wrong : An assignment statement is used to attempt to assign a string to an array of characters . for example : char a[6]; a = "Hello"; ( The reason for the error is that the array name is a constant , Can't point to another storage space ) Error 2 : After the pointer variable is defined, call strcpy The function attempts to copy a string into the storage space indicated by the pointer . for example : char *p; strcpy(p, "Hello");

( The reason for the error is the pointer p In this case, a random address value is stored , That is, it has not pointed to a valid storage space between , It makes no sense to assign a string constant to a random storage space .)

(3)" Character arrays hold strings " And " Pointer to string " Comparison For string operations , You can use character arrays , You can also use character pointer variables , There are some similarities and differences between them : The same thing : You can use the initialization method to assign a string constant to it . for example : char a[6] = "Hello"; ( correct ) char *p = "Hello"; ( correct ) Difference 1: Character arrays cannot be assigned string constants with assignment statements ; The character type pointer variable can be made by assignment statement

Point to string constant ; for example : char a[6]; a = "Hello"; ( error ) char *p; p = "Hello"; ( correct ) Difference 2: After the character array is defined, you can call strcpy Function to assign a string constant to it ; The character type pointer variable does not

Can immediately call strcpy Function to assign a string constant to it . for example : char a[6]; strcpy(a, "Hello"); ( correct ) char *p; strcpy(p, "Hello"); ( error ) Difference 3: After the character array loads the string , The system opens up a continuous storage space for arrays ( Greater than or equal to string length

degree ), The array name represents the first address of this storage space . After the character pointer variable points to the string , The system is character type Pointer variables just open up 4 Bytes , It is used to store the first address of nameless storage area of string . for example :÷ char a[ ] = "Hello"; ( The system opens up 6 Two bytes of storage space for Strings ) char *p = "Hello"; ( The system is a pointer variable p Opens the 4 A byte is used to store the first address of a string constant ) therefore sizeof(a) The result is 6; and sizef(p) The result is 4.

(4) Array of strings difficulty

Multiple strings together make up an array of strings . You can use a two-dimensional array ( Character type ) To construct an array of strings ,

You can also define an array of pointers ( Character type ) To construct a similar string array . The following are respectively described : Method 1 : Using two-dimensional arrays to construct string arrays . for example : char name[ ][10] = {"China", "America", "English", "France"}; When you define a two-dimensional array , You can default the length of the first dimension , In this case , The system is a two-dimensional array name A total of 40

Bytes of storage space , Used to hold four strings , Although some units are wasted , The schematic diagram is shown below :

name name[0]

name[1]

name[2]

name[3]

C h i n a \0

A m e r i c a \0

E n g l i s h \0

F r a n c e \0

Method 2 : Define an array of pointers to construct an array of strings . for example : char *pname[4] = {"China", "America", "English", "France"};

pname pname[0]

pname[1]

pname[2]

pname[3]

C h i n a \0

A m e r i c a \0

E n g l i s h \0

F r a n c e \0

It can be seen from the above diagram that , Pointer array pname There are four elements in , All character type pointer variables , Each pointer points to The storage space to is not equal . Therefore, the string array constructed by pointer array can effectively use the storage space , According to different strings The length system allocates different storage capacities for it , So there is no waste of storage space , This is similar to the string constructed by a two-dimensional array Arrays are different .

The sixth part " Further discussion of functions " Knowledge point

1、main The parameters of the function ( The teaching material 11.1 section ) main The arguments to a function usually have two , The first part of a function can be written in the following form : The first parameter : Type must be int type , The parameter name is usually argc, It can also be named by the user himself . This parameter records the number of strings entered by the user from the command line . The second parameter : The type must be a pointer array of character type , The parameter name is usually argv, It can also be named by the user himself . This parameter records the strings entered by the user from the command line , Because multiple strings form a string array , In this case, the formal parameter is an array of pointers , Count

Each pointer in the group points to the first address of each string . explain : From multiple strings entered from the command line , The first string must be the file name of the executable .

See the textbook "P158 example 11.1" For parameters argc and argv Use .

2、 Pointer to function ( A function pointer )( The teaching material 11.2 section )

(1) The definition of a pointer variable to a function 、 assignment

A pointer to a function is also called " A function pointer ", because C In language, the function name represents the entry address of the function , So you can define a pointer to the function to store the entry address , Call this pointer a pointer to a function .

void main(int argc, char **argv){ … }

difficulty

a key

double fun(int a, char *p){ … }

The fun Function defined as the return type is double type , There are two parameters , The first is int type , The second is char * type .

{ … } void main(int argc, char *argv[ ])

perhaps

void main(void){ double (*pfun)(int, char *); // Define pointer variables to functions

char x=2, double y; pfun = fun; // take fun The entry address of the function is assigned to the pointer variable pfun …

y = (*pfun)(10, &x); // Equivalent to y = fun(10, &x); }

In the above diagram , In the main function, we first define a pointer variable to the function pfun, Explicitly indicate that the return value of the function pointed to by the pointer is double type , Function has two arguments , The first parameter is int type , The second parameter is char * type . Then change the pointer to

The amount pfun assignment , Pass statement "pfun = fun;" take fun The entry address of the function is assigned to the pointer variable pfun, So the function can be called through the pointer . The use of pfun Realize to fun Function call , Pass statement "y = (*pfun)(10, &x);" To complete , This statement is equivalent to the traditional usage "y = fun(10, &x)".

Be careful 1: Define pointer variables to functions pfun when ,"* pfun" You have to put parentheses around , It's written in (* pfun). Be careful 2: When assigning a value to a pointer variable to a function , The left side of the assignment number only writes the name of the pointer variable pointing to the function , The right side of the assignment number is just

Write the function name . Be careful 3: When a function is called with a pointer variable to the function , Equivalent to calling a function with a function name .

(2) A pointer to a function variable as an argument When a function name is used as an argument , The corresponding parameter should be a function pointer . Function pointers can also be used as function arguments , The corresponding formal parameter should be a pointer variable of the same type . See the textbook "P159 example 11.2".

3、 Recursive call of function ( The teaching material 11.3 section ) a key

If a function calls itself , Is called direct recursive call ; If two functions call each other , It's called indirect recursion

call . A function that calls itself within its body is called a recursive call . This function is called a recursive function . stay

Recursive call , The main tuning function is the tuned function . Executing a recursive function will call itself repeatedly . For example, there are functions

fun As shown in the figure below :

int fun (int x) {

int y; z=fun(y);return z;

}

This function is a recursive function . But running this function will call itself endlessly , Of course that's not true

Of . In order to prevent recursive calls from happening without termination , There must be means within the function to terminate the recursive call . frequently-used

The way is to add conditions to judge , When a certain condition is satisfied, it will not be called recursively , Then go back to .

Part seven " Structure 、 Shared body " Knowledge point a key

1、 A description of the type of structure

" Structure " It's a construction type , It's fixed by the number , A set of ordered variables of the same or different types . Every data that makes up a structure is called the structure's " member ", Or called " component ". The form of structure type description is as follows : struct Structure identifier

for example : The following defines a date structure type { struct data { int year; int month; int day; };

Type name 1 List of structure member names 1; Type name 2 List of structure member names 2; … Type name n List of structure member names n;

} ; explain 1: Descriptions of structure types can be nested . explain 2:struct Is the key word ." Structure identifier " It can be omitted . explain 3: The semicolon after the curly bracket on the right ; Don't omit . explain 4: The description of structure type only lists the composition of the structure , It marks the existence of this type of structural pattern , Compiler

The order does not allocate any storage space for this . It's like listing "int", The marking system recognizes this data type , but "int" It does not take up memory space , Only defined int After the variable of type , The system allocates memory space for variables .

2、 use typedef Definition type

typedef It's a keyword , It can be used to give a new name to an existing data type , It can be understood as giving an alias to an existing data type .

for example :typedef int INT; INT x, y; // Equivalent to int x, y; The above writing means to use typedef For existing data types "int" Took a new name "INT", therefore "INT" Equivalent to "int",

You can use this new type name to define variables x and y. Be careful :typedef The use of is not to define a new type , It just takes a new name for the existing data type . User defined structure types are generally complex , Use typedef You can take a simpler name for the structure type . There are three ways to use typedef A method to take an alias for a struct type . An alias for "DATE".

Method 1 : First define the structure type , Reuse typedef Give it an alias . struct date { int year; int month; int day; }; typedef struct data

Method 2 : Define the structure type Method 3 : Defining structure types while using typedef At the same time typedef for that Give it an alias , And don't omit Take an alias , And the structure identifier is omitted . typedef struct date { int year; int month; int day; }DATE; DATE;

Structure identifier . typedef struct { int year; int month; int day; }

chart 1 chart 2 chart 3

DATE;

3、 Define structure variables

After the definition of structure type mentioned above , The system only recognizes that there is such a complex data type constructed by users themselves , But not for it Allocate storage space , Only after the variable of the structure type is defined , The system allocates the corresponding storage space for the variable , Structural variables account for

The storage capacity used depends on the type of structure . Here are a few ways to define structure variables : Method four : First, define the struct class

Method 1 : First define the structure type , Then define the variable of the structure type . struct date { int year; int month; int day; }; struct data

Method 3 : First use typedef type , And then use typedef Method 2 : In defining knots At the same time of the construction type , Define the alias of the structure type , Take an alias , Finally, don't

Name defines the structure variable . struct date { int year; int month; int day; }; typedef stuct date DATE;DATE x, y;

chart 7

Define structure variables . Then use the structure type struct date { int year; int month; int day; }

chart 5

Names define variables . typedef struct date { int year; int month; int day; }DATE; DATE

chart 6

x, y;

x, y; x, y;

chart 4 Students carefully compare " chart 1" and " chart 4", If the structure type name "struct date" There are keywords in the front typedef, be struct date

Next is the alias for the structure type , On the contrary, if there are no keywords typedef, be struct date And then there are structural variables . Compare carefully " chart 2" and " chart 5", In the same way , If "struct date" There are keywords in the front typedef, The right flower

After the brackets is the alias for the struct type , On the contrary, if there are no keywords typedef, After the curly brackets on the right is the structure variable . Above 4~ chart 7 All three methods define variables of two struct types x and y, Each of these two variables occupies 12 A byte of memory

Storage capacity , The size of the storage capacity is determined by the structure type .

4、 Pointer variables that define structure types

The definition method of pointer variable of structure type is the same as that of ordinary variable of structure type , You can use graphs 4~ chart 7 Shown

Three methods , for example :

typedef struct student { char num[20]; char name[30]; char sex; int age; double score; }STU; STU x, *p = &x;

The figure on the right defines a STU Common variables of structure type x, And pointer variables p. Because each member of the structure type occupies 20+30+1+4+8=63 Byte storage capacity , So the system is a variable x Distribute 63 Byte storage space , The pointer p The base type of is STU Type of structure , I.e. pointer p The segment of storage space pointed to is 63 byte .

Define structure pointer variables p And initialize it at the same time , Assign it to "&x", This assignment process is necessary , Because it makes the pointer variable p Points to a valid storage space , You can't use a pointer without a valid storage space .

5、 Reference members through struct variables or struct pointers

For example, as defined in the figure above STU Structure variable of type x Or structure pointers p, They have five members , If you want to take out a member for operation , Can't be used directly , for example "age = 20;" Such a statement is wrong , as a result of age Now it's not an independent variable , It's a variable x A member of , Or an attribute , To remove age And assign it to 20, It has to be through variables x Or pointer p To take it out . There are three ways , be used "." Operator or "->" Operator .

(1) Structure variable name . Member name (2) Structure pointer variable name -> Member name

a key

(3)(* Structure pointer variable name ). Member name for example : strcpy(x.name, "LiWei"); perhaps strcpy(p->name, "LiWei"); perhaps strcpy((*p)->name, "LiWei"); x.age = 20; perhaps p->age = 20; perhaps (*p).age = 20;

6、 Assign values to structure variables

Method 1 : initialization Define structure variables and assign initial values to its members at the same time , Called initialization , for example :

typedef struct student { char num[20]; char name[30]; char sex; int age; double score; }STU; STU

The figure on the right shows how to define the structure variable x At the same time, give initial values to its five members . All initial values must be

Enclosed in a pair of curly brackets , The values are separated by commas

separate , The type and writing order of values are related to each member

The type and order of writing are consistent .

x={"20070102001", "ZhangHua", 'M', 18, 80.0};

Method 2 : The global assignment of structural variables . If two struct variables are of the same type , Then the two structural variables can be integrated

assignment . for example :

typedef struct student { char num[20]; char name[30]; char sex; int age; double score; }STU; STU x, y={"20070102001", "ZhangHua", 'M', 18, 80.0};x = y; // The global assignment of structural variables

The figure on the right defines two structure variables x and y. Among variables y The initialization method has been used to assign initial values to its five members , Variables x At the time of definition, each member has no initial value . because x and y Is a variable of the same type , So you can use the assignment statement "x = y;" Put the variable y The value of is assigned to the variable as a whole x. This is equivalent to changing the variable y The initial value of each member is assigned to the variable x The members of .

Method 3 : Each member of a structure variable is assigned a value separately . The corresponding members of two structure variables can assign values to each other , for example : strcpy(x.num, y.num); strcpy(x.name, y.name); x.sex = y.sex; x.age = y.age; x.score = y.score; Be careful : When the above members are assigned separately , For string types , Can not write "x.num = y.num;"、"x.name = y.name;",

Although both sides of the assignment number are of the same type , All array names ( It's the address ), But because the array name itself is an address constant , It cannot be assigned

The first address of another storage space , Therefore, for assignment between members of character array type , Should be selected strcpy Library function . Members of other basic data types can be assigned directly by using assignment statements .

Method four : Enter values for each member from the keyboard . for example : scanf("%s", x.num); // Be careful : member "x.num" Itself is an array name , Representative address , Therefore, the address symbol is not added in the front scanf("%s", x.name); // member "x.name" Itself is an array name , Representative address , Therefore, the address symbol is not added in the front scanf("%c", &x.sex); // member "x.sex"、"x.age"、"x.score" Is a variable of the basic data type , Add the address symbol in front of it scanf("%d", &x.age); scanf("%lf", &x.score);

7、 Structure variables or members as arguments

" Pass value " The way —— As with basic data types , When a struct variable or a member of a struct variable takes an argument , What we achieve is " Pass on

value " The way , Data can only be passed in one direction . The corresponding formal parameter must be of the same type as the actual parameter . " Address " The way —— When the address of a structure variable or the address of a member of a structure variable is used as an argument , What we achieve is " Address "

The way . The corresponding formal parameter must be a pointer variable of the same type . difficulty 8、 Using structural variables to form a linked list

When a struct type is defined, it has a pointer variable of its own struct type as a member , Then you can use the variable of the structure type to construct

Make a linked list . There are two ways to form a linked list: static and dynamic , Dynamic mode is the difficulty , It is also the focus of the examination . When constructing a one-way list , Usually there is a head node , Several data nodes , And an end node . Generally speaking , The number of head nodes

The data field is empty , The pointer field of the head node points to the first data node , By analogy , The pointer field of each data node points to the next data node

spot , The last data node is called the end node , The pointer field of the end node is empty (NULL). About the basic algorithm of one-way linked list ( Reference materials P198~P201) Yes : The establishment of linked list 、 Access the data of each node in the linked list in sequence

Domain 、 Insert a node into a one-way list 、 Delete a node in a one-way list . The operation of linked list must consider the purpose of each pointer variable .

9、 Shared body

The description of Commons types and the definition of Commons variables are similar to that of structs . The difference between Commons and structures is , Structural variable

Each member of the system occupies its own storage space , Each member of a common body variable occupies the same storage space . explain 1: The size of the shared volume variable is determined by the member with the largest number of bytes . explain 2: When a Commons variable is initialized, only its first member can be initialized . explain 3: Because all members of a common volume variable occupy the same storage space , So they have the same initial address , And with the ground of the variable

Same address . Each member of a Commons variable is referenced exactly the same way as a struct , There are three ways to use : (1) Common body variable name . Member name (2) Common body pointer variable name -> Member name (3)(* Common body pointer variable name ). Member name

Part eight " file " Knowledge point

1、 Basic concepts

(1) A collection of data recorded on an external medium is called " file ". Data can be stored on media in text or binary form , Therefore, files can be divided into text files and binary files according to the storage form of data . The input and output speed of binary file is faster .

(2) The input and output mode of a file is called access mode , stay C In language , There are two ways to access —— Sequential access 、 Direct access . Sequential access is characterized by : Whenever such a file is opened for reading or writing , Always read or write from the beginning of the file . Direct access is characterized by : You can call the library function to specify the start position of the read or write , Then read or write directly from this location . (3) The file pointer : Is a structure type named FILE The pointer to . The opening of a file 、 close 、 read 、 Write and other operations are

It has to be done with the help of a file pointer . for example :FILE *fp; That is to say, it defines a FILE File pointer to structure type . (4) File location pointer : It's just a visual concept , Used to indicate the position of the data currently read or written in the file . Read or write

The operation always starts at the location indicated by the file location pointer .

2、 File operation class library function

File operation class library functions are defined in stdio.h In the header file . (1) fopen and fclose function —— open 、 Close file

Function call form : The file pointer = fopen( file name , How files are used ); fclose( The file pointer ); explain 1:fopen The parameter file name and file usage of the function are strings . When the function is successfully called, it returns a

FILE Pointer to type . The common ways of using files and their meanings are shown in the following table : How files are used meaning

"r"、"w" As read-only 、 Write only and open a text file . Always read and write from the beginning of the file . "r+"、"w+" Open a text file for reading and writing . "a" Open a text file to add content to the back of the file . The original content of the document remains unchanged .

Text file

"a+" After adding content at the end of the file , You can read from the beginning .

"rb"、"wb" Read only 、 Write only and open binary . Always read and write from the beginning of the file . "rb+"、"wb+" Open binaries for reading and writing . "ab" Open the binary file to add content to the back of the file . The original content of the document remains unchanged .

Binary system file

"ab+" Same as "a+", After adding content at the end of the file , It can be read from the specified location . explain 2: When reading a file 、 After the write operation is complete , Must call fclose Function close file . (2) fscanf and fprintf function —— Format input and output .

Function call form :fscanf( The file pointer , Format control string , Input item list ); fprintf( The file pointer , Format control string , List of output items ); function :fscanf The function reads formatted data from a file ,fprintf The function writes formatted data to a file . explain : These two functions are related to scanf、printf Functions have similar functions , Table 1 compares the four functions . Function name Function and data flow Function name Function and data flow scanf keyboard Memory printf Memory display fscanf file Memory

Input Format data fprintf Memory file

Output Format data

Table 1

(3) fgetc and fputc function —— It can also be written as getc、putc. The function is to input 、 Output a character . Function call form :ch = fgetc( The file pointer ); //ch It's a character variable fputc(ch, The file pointer ); function :fgetc( or getc) The function reads a character from a file ,fputc( or putc) Function is to output a character

To the file .

explain : These two functions are related to getchar、putchar Functions have similar functions , Table 2 compares the differences between the four functions . Function name Function and data flow Function name Function and data flow getchar keyboard Memory putchar Memory display

fgetc file Memory Input

A character fputc Memory file Output

A character Table two

(4) fgets and fputs function —— Input 、 Output a string . Function call form :fgets(str, n, The file pointer ); //str Is the starting address of the string ,n Represents the length of the string read in fputs(str, The file pointer ); function :fgets The function reads a string from a file ,fputs The function outputs a string to a file . explain 1:fgets Functions can only be read from a file at most n-1 Characters , After reading in , The system will automatically add '\0'. explain 2: These two functions are related to gets、puts Functions have similar functions , Table 3 compares the differences between the four functions . Function name Function and data flow Function name Function and data flow

gets keyboard Memory puts Memory display fgets file Memory

Input character string fputs Memory file

Output character string

Table 3

(5) fread and fwrite function —— read 、 Write binary . Function call form :fread(buffer, size, count, The file pointer ); fwrite(buffer, size, count, The file pointer ); Parameter description : The parameters in the above functions buffer Is a pointer to a data block , Data input or ready to be output is stored in this

In the block ;size Represents the number of bytes per data block ;count Used to specify each read 、 Number of data blocks written . explain :fread and fwrite These two functions can only read and write binary files , Cannot manipulate text file .

(6) feof function —— Used to determine whether the binary file ends , If so, return 1, Otherwise return to 0. Function call form :foef( The file pointer ); explain : The text file is based on EOF( amount to -1) As the end of the file . There is no obvious end to binaries

sign , To determine whether the binary ends, you must call feof function . (7) fseek function —— Used to move the file location pointer to the specified location , The next read or write operation starts from this position .

Function call form :fseek( The file pointer , offset, origin); Parameter description : The parameters in the above functions offset Is the displacement in bytes , It's long ;origin It's the starting point ,

It is used to indicate which position the displacement is based on , The starting point can be an identifier ( Table 4 ) To express , It can also be expressed in numbers .

Identifier of the starting point of the position pointer The starting point of representation Numbers SEEK_SET File start 0 SEEK_END end of file 2 SEEK_CUR File current location 1

Table 4

explain 1: For text files , Displacement offset Must be 0. for example :fseek(pf, 0L, SEEK_SET); Express Move the file location pointer to the beginning of the file ;fseek(pf, 0L, SEEK_END); Move the file location pointer to To the end of the file ;

explain 2: For binary files , If the displacement is a positive integer , Indicates that the position pointer moves backward from the specified starting point dynamic ; If the displacement is a negative integer , Indicates that the position pointer moves forward from the specified starting point .

(8) ftell function —— Used to get the location of the current file location pointer , The return value of this function is a long integer number , Represents the number of bytes of the current position pointer relative to the beginning of the file . Function call form :t = ftell( The file pointer ); //t It's a long integer variable

(9) rewind function —— also called " Reverse winding " function , The function is to make the position pointer of the file return to the beginning of the file . Function call form :rewind( The file pointer );

Common library functions

1、 Standard I / O functions ( The header file stdio.h) Function name The function prototype function

scanf scanf( Format control , List of address entries ) Enter formatted data from the keyboard printf scanf( Format control , List of output items ) Output the formatted data to the display screen getchar char getchar(void) Read a character from the keyboard putchar putchar(char ch) Output a character to the screen gets gets(char *s) Read a string from the keyboard , Can contain spaces puts puts(char *s) Output a string to the screen

2、 Mathematical functions ( The header file math.h) Function name The function prototype function

sqrt double sqrt(double x) Calculate and return parameters x The square root of pow double pow(double x, double y) Calculate and return parameters x Of y The value of the power fabs double fabs(double x) Calculate and return parameters x The absolute value of log double log(double x) Calculate and return parameters x Logarithm of , The o ln(x) Value

3、 String handling functions ( The header file string.h) Function name The function prototype function

strlen int strlen(char *str) Calculation str The length of the string in question , barring '\0' strcpy strcpy(char *dest, char *sour) take sour The string in question is copied to dest In the storage space strcat strcat(char *dest, char *sour) take sour The string in question is pasted into dest The end of the string in question

strcmp int strcmp(char *str1, char *str2) Compare str1 and str2 The two strings referred to , And return the result of the comparison . If the former > the latter , return 1; If the former < the latter , return -1; If the former == the latter , return 0.

4、 Dynamic storage allocation function ( The header file stdlib.h) Function name The function prototype function

malloc void *malloc
版权声明
本文为[Yang Hengchang]所创,转载请带上原文链接,感谢
https://fheadline.com/2021/02/20210223100511648i.html
相似文章

2021-08-09