MindMap Gallery C language
This is a mind map about C language, and its main contents include: pointers, functions, arrays, loops, switch statements, if statements, logical operators and logical expressions, relational operators and relational expressions, simple C programs, data types, operators and expressions, overviews, and exam questions.
Edited at 2025-03-01 10:32:53Rumi: 10 dimensions of spiritual awakening. When you stop looking for yourself, you will find the entire universe because what you are looking for is also looking for you. Anything you do persevere every day can open a door to the depths of your spirit. In silence, I slipped into the secret realm, and I enjoyed everything to observe the magic around me, and didn't make any noise. Why do you like to crawl when you are born with wings? The soul has its own ears and can hear things that the mind cannot understand. Seek inward for the answer to everything, everything in the universe is in you. Lovers do not end up meeting somewhere, and there is no parting in this world. A wound is where light enters your heart.
Chronic heart failure is not just a problem of the speed of heart rate! It is caused by the decrease in myocardial contraction and diastolic function, which leads to insufficient cardiac output, which in turn causes congestion in the pulmonary circulation and congestion in the systemic circulation. From causes, inducement to compensation mechanisms, the pathophysiological processes of heart failure are complex and diverse. By controlling edema, reducing the heart's front and afterload, improving cardiac comfort function, and preventing and treating basic causes, we can effectively respond to this challenge. Only by understanding the mechanisms and clinical manifestations of heart failure and mastering prevention and treatment strategies can we better protect heart health.
Ischemia-reperfusion injury is a phenomenon that cellular function and metabolic disorders and structural damage will worsen after organs or tissues restore blood supply. Its main mechanisms include increased free radical generation, calcium overload, and the role of microvascular and leukocytes. The heart and brain are common damaged organs, manifested as changes in myocardial metabolism and ultrastructural changes, decreased cardiac function, etc. Prevention and control measures include removing free radicals, reducing calcium overload, improving metabolism and controlling reperfusion conditions, such as low sodium, low temperature, low pressure, etc. Understanding these mechanisms can help develop effective treatment options and alleviate ischemic injury.
Rumi: 10 dimensions of spiritual awakening. When you stop looking for yourself, you will find the entire universe because what you are looking for is also looking for you. Anything you do persevere every day can open a door to the depths of your spirit. In silence, I slipped into the secret realm, and I enjoyed everything to observe the magic around me, and didn't make any noise. Why do you like to crawl when you are born with wings? The soul has its own ears and can hear things that the mind cannot understand. Seek inward for the answer to everything, everything in the universe is in you. Lovers do not end up meeting somewhere, and there is no parting in this world. A wound is where light enters your heart.
Chronic heart failure is not just a problem of the speed of heart rate! It is caused by the decrease in myocardial contraction and diastolic function, which leads to insufficient cardiac output, which in turn causes congestion in the pulmonary circulation and congestion in the systemic circulation. From causes, inducement to compensation mechanisms, the pathophysiological processes of heart failure are complex and diverse. By controlling edema, reducing the heart's front and afterload, improving cardiac comfort function, and preventing and treating basic causes, we can effectively respond to this challenge. Only by understanding the mechanisms and clinical manifestations of heart failure and mastering prevention and treatment strategies can we better protect heart health.
Ischemia-reperfusion injury is a phenomenon that cellular function and metabolic disorders and structural damage will worsen after organs or tissues restore blood supply. Its main mechanisms include increased free radical generation, calcium overload, and the role of microvascular and leukocytes. The heart and brain are common damaged organs, manifested as changes in myocardial metabolism and ultrastructural changes, decreased cardiac function, etc. Prevention and control measures include removing free radicals, reducing calcium overload, improving metabolism and controlling reperfusion conditions, such as low sodium, low temperature, low pressure, etc. Understanding these mechanisms can help develop effective treatment options and alleviate ischemic injury.
No relevant template
C language
Exam question type
Single choice question
Judgment question
Fill in the blanks of the program
Program Analysis
Programming questions
Overview
Computer Development
Development of programming languages
The development of C language
Characteristics of C language
Intermediate Language
Access to hardware
Programmer language
Rich transport characters, high code quality, good portability
Modular design language
C language program structure
illustrate
The composition of program C
The function consists of two parts
Program execution
Statement
Programming style
Overall structure Alignment
Definition of identifier, please understand the meaning of
Comments
Steps to go to the machine
edit
Source program input
Modify the source program
save
Compilation
Check for syntax errors
Generate target program .obj
Link
Library functions
implement
.exe
Data types, operators and expressions
Program = Data Structure Algorithm Programming Method Programming Language and Environment
Data Type
Basic Type
Integer
Character type
Real type
Construct Type
Array
Structure
Shared body
Enumeration type
Pointer type
void type
Function Type
Constants and variables
constant
The amount whose value will not change during the execution of the program
Direct constants (literal constants)
Symbol Constants
variable
The amount whose value can be changed
The variable has a name
Allocation of storage units at compile time
Identifier
An identifier is a name
Classification
Keywords
Predefined identifiers
printf
scanf
User Identifier
Made of alphanumeric underline
The beginning can only be made with letters or underscores
Cannot be repeated with reserved words
case sensitive
Pay attention to length
Definition of variables
Define first and then use
The format defined
Type name Variable name 1, Variable name 2;
Location
Global variables
Outside the function
Local variables
Generally at the beginning of the function
Starting with compound statement
Data Type
Integer data
Integer constants
Decimal
123, -456
Octal
Start with 0 (zero)
011 =》9
-017=》-15
018, 019=》Wrong
hexadecimal
Start with 0X
Add L or l (lower case) to be considered as long integer constant
0L
Add U or u afterwards, it is unsigned unsigned
123U
Integer variables
int a;
VC 6.0 takes up 4 bytes in memory
Classification
Modifier
signed
unsigned
Short
2 bytes
long
4 bytes
Real data
Real constant
Real numbers are also called floating point numbers
Expression form
Decimal
Consisting of numbers and decimal points
0.123 .123 123.
Index form
123e3 or 123E3 =》123*10^3
Note: There must be a number before and after e, and the exponent after e is an integer
For example: e3, 2.13e3.5, .e, e
Real variables
Single Accuracy
float
4 bytes
Valid numbers 6-7
Double precision
double
8 bytes
15-16
Long double precision
long double
Character data
Character constants
A character enclosed in single quotes
For example: 'A', 'a' are different, '' two consecutive single quotes are wrong
Escape characters
Characters of special forms begin with "\"
' ', '\t',
'\ddd' ASCII characters corresponding to 1-3 digit octal
char ch = '\101';
‘\xhh' 1-2-bit hexadecimal
char a = '\x61';
Character variables
Used to store character constants, only one can be stored, accounting for 1 byte
Definition form
char character variable 1, character variable 2;
char c1, c2; c1 = 'a'; c2 = 97;
The storage form of character data in memory
Store the ASCII code corresponding to this character
Similar to integers, they can be used as integers
0-127 The highest bit is 0, and the output is positive with %d. 128-255 The highest bit is 1, and the output is negative with %d.
String constants
Sequence of characters enclosed in double quotes
Note: The difference between “a” and “a”
Two consecutive "" are correct
the difference
Different representation
Double quotes
Single quotes’
Sub-theme 3
Different definitions
char ch; character variables store character constants
Character array storing strings
Quote
The two cannot be cited by each other
Store in memory
1 byte in memory
String: Ended with '\0' Number of bytes occupied in memory = actual character length 1 For example: "CHINA" has 5 characters, accounting for 6 bytes in memory
Features
Only string constants and no string variables
A string ends with '\0', without '\0', it cannot be called a string.
4 zeros
0
Number 0, accumulator, counter, subscript of array
'\0'
The ending character of the string, the ASCII code value is 0, and the characters cannot be displayed.
NULL
Generally used for pointer assignment, pointer is empty
‘0’
Character 0, ASCII value 48
char-char =》int
'7' - '0' => 7
char int => char
//Case conversion char ch = 'B'; char st = ch - 'A' 'a'; st = 'a' 'A' - ch
char char meaningless
Variable assignment
Assigning an initial value to a variable when defined is called initialization
int a = 10;
int a; a = 10;
int a, b, c=10;
int a, b, c; c = 10;
int a = b = c = 10; wrong
int a, b, c; a = b = c =10;
Know the radius to find the perimeter, area, and volume of the ball
Symbol Constants
definition
#define PI 3.14
Replace 3.14 with PI
Features
Simplified writing, easy to read
Easy to modify
illustrate
Generally, uppercase and lowercase variables
Scope
Start with #define
End at #undef or end of file
The value of symbol constants cannot be modified within scope
const double PI = 3.14;
Mixed operations of various numerical data
Mixed operations
High double
←float
↑long
↑unsigned
Low int
←char, short
Horizontal arrows indicate necessary conversions
For example, two variable operations of float type must be converted to double first and then operation, and the result is double type
Vertical arrows indicate the direction of conversion
Int and double operations, convert int directly into double and double operations, and the result is double
Calculation results
The highest type of operation involved
practise
ch/i f*d - ( f i )
Arithmetic operators and arithmetic expressions
Operator characteristics
Arithmetic operators
composition
- * / % --
%module operator
The operation object can only be integer
The result is the same as the symbol of the dividend
Application: Disassembly
n = 123 Take out single, ten and hundreds respectively
Single digit n Ten digit n/10 n 0/10 Hundred digit n/100
Divided by 10, downgrade
Find more than 10, get a single position
Operator priority and nodule
Evaluation first depends on priority
() Single item
The priority is the same, depending on the combination
Combination of left: conforms to arithmetic operation rules, from left to right
Right combination:
Monograph
Assignment operator
Conditional operator
practise
The following set of operators is arranged from high to low _____
Cast type conversion (display conversion)
5.7%3 =》?
Format (type name) (expression)
For example: (int) 5.7%3
(double)x y
Convert the result of x y into double?
(double)(x y)
Convert x to double and add it to y
use
Function parameters
Notice
Unsafe conversion
High precision -》Low precision, direct intercept (not rounding)
Low precision-》High precision, supplement 0
Temporary one-time
(int)x y
After converting the x value to int, add it with y, the value of x itself remains unchanged
double x = 5.7 (int)x 3.2 Result: 5 3.2 = 8.2 x is 5.7 unchanged
Self-increase and self-decrease operator
Monologic operator, --
Operation object: can only be used for variables, and it is also an assignment operation itself
3, (a b) Wrong
i = 3;
j = i ;
Operator, on the right, first use the value of i, and then i completes the operation of adding 1
j = i;
i = i 1;
j = i;
Operator On the left, first complete the operation of adding 1 to i, and then assign the value of i (after 1) to j
i = i 1;
j = i;
practise
int a = 3; while( a-- ) printf("%d ", a ); printf(" out while %d", a ); 2 1 0 out while -1
int a = 3; while( --a ) printf("%d ", a ); printf(" out while %d", a ); 2 1 out while 0
Notice
Binding right binding, from right to left
int a = 3; printf(" %d ", -a ); printf(" %d ", a );
i ; and i ;
No difference, complete i=i 1;
Assignment operators and assignment expressions
Assign symbol =
Format: Variable name = expression
Function: Assign the value of the right expression to the variable on the left
If a = 10 assign 10 to a, perform an assignment operation (put 10 into a memory unit of a)
Notice
Binding: Right binding
The left side must be an invariant, not a constant or an expression
d = a b = c 10; wrong
Mutual assignments between different data types
Real type (float, double) is given to integer type (int), discarding the decimal part, not rounding, need to round 0.5
int=》float, double, the value remains unchanged, stored in floating point form, and the tail is supplemented by 0
char=》int , char1 bytes, int 4 bytes, put into the lower 8 bits
Unsigned and unsigned of the same type as each other
double=》float intercepts the first 7 valid numbers of double to float
practise
Keep the floating point number n and the 3rd digit rounded. If n=3.4567, the result is: 3.46
Compound operator (arithm character assignment operator)
Priority
Bondability (right)
constitute
=, -=, *=, &=, ^=, != (relationship)
Notice
x = 3;
x = x 3;
x *= y 3;
x = x *(y 3)
There are several items on the right side of the assignment number, which is equivalent to brackets.
practise
a=3; a = a -= a * a
Assignment expression
Assignment is an operator
Right combination
The expression has a value
Comma expressions and comma operators
Format: Expression 1, Expression 2
Solving process
Comma, left combination
The lowest priority
First solve expression 1,..., use the value of the rightmost expression as the value of the entire comma expression
practise
x = ( y=3, 4*5 )
x value 20
x = y=3, 4*5
x value 3, the value of the entire comma expression is 20
use
Expression concatenation
for( i=1,j=100; i<j; i ,j-- );
Delimiter
int x, y;
Find the length operator
sizeof (variable|constant|type)
Find the number of bytes occupied by this type in memory
malloc( sizeof( struct link ) )
Simple C program
Overview of C statements
Control statements
Function call statement
Function (real parameter table list);
scanf("%d", a);
Expression statement
Abortion statement
Compound statements
Enclosed in {}
Notice
In grammar is equivalent to a statement, as a whole
The start part of the compound statement can define variables
After the compound statement, no need to add it;
Three basic structures of the program
Sequential structure
Select (branch) structure
Loop (repeat) structure
Assignment statement
statement;
Difference from expressions
Expressions have values
Data input/out
There are no input and output statements, only input and output functions
stdio.h header file
Standard input and output header file
Output
putchar(ch) character output function
Output a character to the terminal
ch can be a char, int constant, variable, expression
printf (format control, output table column)
Format control is a string enclosed in double quotes
Format description
% and format characters %d
Normal characters
Output as is, space comma
Format characters
Different data types, different format characters
D format
Output decimal integer
%d outputs according to actual length
%md, m output field width, if the actual number of digits is less than m, fill the space on the left (right aligned) If the actual number of digits is greater than m, break through
%-md - (negative sign) alignment, left alignment (right space filling)
%ld long integer, %hd short integer
O format
Output in octal form
Sign bits are output together
X format
Output in hexadecimal form
%lx
U format
Unsigned output, decimal
C format
Used to output a character
The character memory occupies one byte, and the ASCII code is stored. 0-255 can be output according to the numerical value.
s format
Used to output a string
%s until we meet '\0'
%ms
%-ms
%m.ns
The output occupies m columns and takes the first n characters of the string
%-m.ns
F format
Used to output real numbers, floats and doubles, output in decimal form
%f
All integer parts are output and 6 decimal places are output.
Notice
Not all values are valid
%m.nf
The output occupies m column, where n decimal places
Notice
One decimal point is also
When taking n bits, the first bit cut is rounded
%.0f does not output a fractional part
%-m.nf
e-format
Output real numbers exponentially
%e
The system specifies 6 decimal places, the exponent part occupies 3 places, e accounts for one place, and ± accounts for one place
%m.ne
g format
Used to output real numbers, automatically select the shortest width in f or e format
Make the output number predecessor positive and negative sign
printf("% 5d% d ", a, b );
Notice
Lowercase characters except X, E, G
Data type matches format characters
type
Number of
Format control strings that can contain escaped characters
d,o,u,x,s,c,f,e,g, after % is the format character, and the others are output as is
Output % and use %%
Different systems vary
enter
getchar()
Character input, enter a character from the terminal
getchar() has no argument
scanf (format control, address table column)
The format control is the same as printf
Format characters
Normal characters are entered as-is
Address table column, address of variable, first address of string
Note: %d%d, spaces, tab keys, and carriage return cannot be used, commas
Format description
Short uses %hd, double uses %lf or %le to enter
For unsigned, you can use %u, %d, %o, and %x to input it.
You can specify the domain width of the input data and the system automatically intercepts it.
% followed by *, indicating that the specified number of columns is skipped
The number of columns can be specified, but the accuracy cannot be specified.
scanf("%7.2f", &f); wrong
Notice
scanf function, the address of the variable should be given
Normal characters are entered as-is
When %c enters characters, spaces and escaped characters are all valid inputs.
When entering data, the following situation is considered to be ended
Encounter space, Tab key, Enter
Encountered with specified domain width=
Illegal input
Relational operators and relational expressions
Relationships are actually more operational
Relational operators
>, >=, <, <=
!=, ==
Priority
Below arithmetic
Bonding
Left combination
Relational expressions
Link any legal expression
Value: is a logical value
True is represented by 1, fake is represented by 0
practise
a = 20; b = 10; the value of a>b is 1
The value of a=3; b=2; c=1; a>b>c is 0
Notice
The two sides are inconsistent, such as int and double operations, the system automatically converts it.
Qualified equality
int a==b?
fabs(a-b)<1e-6
Logical operators and logical expressions
Logical operators
&&, ||,!
Priority
! Monologic operator
Below relationship &&higher than||
Logical expressions
Value: Logical value, true is represented by 1, false is represented by 0
Objects participating in the operation, non-zero represents true, and zero represents false
Notice
Not all logical operations are performed during the solution process
Short circuit phenomenon
practise
if statement
Three forms of if statement
Single branch if statement
Format: if (expression) statement;
Expression: any legal expression
if (3);
Statement: can be a single statement, an empty statement or a compound statement
practise
Output two integers from small to large
Double branch if statement
Format: if (expression) Statement 1; else Statement 2;
Note: else is aligned with if
practise
Even n is true expression
n%2==0
n/2*2 == n
!(n%2)
ch is an English letter
ch>='a'&&ch<='z' || ch>='A'&&ch<='Z'
Judge leap year
Can be divided by 4, cannot be divided by 100, can be divided by 4, can be divided by 400, same as above
year%4==0&&year%100!=0 || year%400==0
year%4==0&&year%100 || !(year%400)
The integers a and b are the same number
a*b>0
Ladder-type if statement
Format: if (expression 1) Statement 1; else if (expression 2) Statement 2;
if( x<0 ) y = -1; else if( x==0 ) y = 0; else y = 1;
Nested if statements
if( x>=0 ) if( x>0 ) y = 1; else y = 0; else y = -1;
Note: if and else pair, starting from the innermost layer, else is always used with the closest, unpaired if on it
Solution:
The embedded if statement also contains else, and the number of if is as many as else
Use curly braces to limit the scope of the embedded if statement
practise
Conditional operator
constitute
? and:
Priority: arithmetic, relation, logic, condition, assignment, comma
Binding: Right binding
Conditional expression
Expression 1? Expression 2: Expression 3
Evaluation order: first solve expression 1, true solution 2, false solution 3, and use this value as the value of the entire expression
Expressions 2 and 3 will only solve one
illustrate
Binding: Right binding
int a = 1, b = 2, c = 3, d = 4; printf("%d ", a>b ? a:c>d ?c:d );
type
The types of expressions 1, 2, and 3 can be different
a>b ? 1.5:2
Value of high type
Relationship with if statement
When the true and false of the if statement are assigned a value to the same variable
if( a>b ) max = a; else max = b;
max = a>b ? a:b;
Switch statement
Handle multi-branches
Format: switch (expression) { case case case 1: statement 1; ... default: statement n 1; }
illustrate
Expressions in brackets after switch are generally, character type, integer type, enum type
The value of the case is the same as the expression type
The function of the case is equivalent to a label, representing the entry, executing the following statement until the end, and there is no matching execution of the following statement after default
The execution of the terminating statement requires break, and the switch statement can be directly jumped out.
Each situation must be different, otherwise it will be contradictory
The order in which each case and default statement appears does not affect the execution result (used in conjunction with break)
Multiple case statements can share a group of statements
practise
cycle
if and goto loop
goto statement
Format: goto statement label;
Statement labels comply with the naming rules of identifiers
goto label;
Notice
After the label, it must be:, placed before a statement and used as the code for the statement.
Jump location
In this function
Generally, it forms a loop with if
Use as little as possible and jump out of multiple loops
for ( ) for() for() if() goto end;
While
Format while (expression) statement;
Features
First judge the value of the expression, execute the statement in true form, and exit falsely
Notice
if, while, for effective range ends at the first semicolon
The statement can be a single statement, a compound statement, or an empty statement.
There should be a statement in the loop body (statement) that makes the loop end
while( 1 ) x ;
A dead cycle
i = 100; while( i>10 ) a b;
The difference between while( x = 'a' ); and while( x=='a' )
k = 2; while( k=0 ) k--;
Loop body execution? Second-rate
practise
1 2 … 100
do-while
Format do statement; while (expression);
Features
First execute the loop body, judge the value of the expression, true execution, false exit
Notice
Difference between while loop
The initial value of a loop variable, while may not execute the loop body at one time. do-while executes at least once.
Similarities
True execution, fake exit
practise
Disassemble and splice
Disassembled number
Get the final number
/10 Reduced level
Scratch number
Low position becomes high, high position becomes low
(0*10) a)*10 b)*10 c
High and low remain unchanged
t = 1; s = n * t; t *=10;
do statement; while( 1 );
A dead cycle
for
Format: for(Expression 1;Expression 2;Expression 3) statement;
illustrate
Expression 1, only 1 time is executed
Each expression can be omitted, and semicolons cannot be omitted
Expressions 1 and 3 can be simple expressions or comma expressions.
practise
Nesting
Multiplication formula table
Print graphics
Exhausted
Comparison of several cycles
Solve the problem
The four loops can be replaced by each other, and the loop composed of if and goto is not recommended.
initialization
while, do-while outside the loop, for expression 1
Termination conditions
while, do-while after while, for expression 2
i = 3; while(i--); while(--i); difference
Execution order
while and for first judge and then execute, do-while execute first and then judge
Break out of the loop
While, do-while, for can be used to break and continue to end this loop
break
Break out of the loop body and end the loop early
practise
Determine prime numbers
Enter a positive integer from the keyboard and output 5 prime numbers greater than or equal to the number. If you enter 17, then output 17, 19, 23, 29, 31
Continue continue
End this loop, skip the statements that have not been executed in the loop body, and judge whether to loop next time (while, for execution expression 3)
Array
One-dimensional array definitions and references
Array is a collection of data elements of the same type. Array name
definition
Data type Array name [Integer constant expression];
Array name: address constant, representing the starting address of the array
int a[10];
#define N 10 int a[N];
Quote
Array name [subscript]
Subscript starts from 0 to N-1
Subscript integer constants, variables, expressions
initialization
All elements assign initial values
int a[3]={1,2,3};
Assign initial values to all elements, you can not specify the length int a[] = { 1,2,3}; int a[] = { 0 };
Some elements assign initial values
int a[10] = { 1,2,3}; a[1]=2, a[3]--a[9] = 0
Some elements omitted are default values
int a[3] = { 0,0,0}; is equivalent to int a[3]={0};
The difference between int a[10]; and static int a[10];
When the array length N and element format M are inconsistent
N>M, only the first M elements of the array are assigned initial values, the rest are default values
N<M, syntax is wrong
application
Inverse order of elements
Fold half search
Sort
Bubble sort
Select Sort
Operation
insert
Move the latter first
delete
Move the front one first
Move (loop left, right)
Two-dimensional array
definition
Data type Array name [Integer constant expression 1] [Integer constant expression 2];
Store in memory by row, line order is preferred
int a[N][M]; N rows, M columns, how many elements are there before a[i][j] i*M j
Quote
Array name [row subscript] [column subscript]
initialization
Same as one-dimensional array, assign initial values one by one element, and are given in sequence
int a[2][3] = { 1,2,3,4,5,6};
All elements can omit the first dimension size
int a[][3] = { 1,2,3,4,5,6,7};
Assign initial values in branch, using curly braces
int a[2][3] = { {1,2,3},{4,5,6}};
int a[2][3] = { {1,2},{3,4},{5,6}};
wrong
Assign initial values to some elements
int a[3][4] = { {2}, {4}, {6} }; int a[3][4] = { {2}, {0,4}, {0,0,6} };
application
Row subscript
Yang Hui triangle
Special square matrix
Spiral square matrix
Character array
definition
char array name [integer constant expression];
initialization
Assign initial values one by one
char ch[] = { 'a', 'b', 'c' };
Specify a string as the initial value
char ch[] = { "hello"};
char ch[] = "hello";
char ch[] = { 'h','e','l','l','o','\0'};
The difference between a character array and a string
Each element in the character array is a character, and the last element is not required to be '\0'
The ending character of the string is '\0'
Input/out of character array
Single character input and output of string
for( i=0; i<5; i ) printf("%c %d | ", ch[i], ch[i] );
Access each element
Input and output of strings
%s format
char ch[80]; scanf("%s", ch ); printf("%s", &ch[3] );
scanf("%s", ch);
Indicates which address the input characters starts to be stored in memory
Enter, TAB key, space end
At the end, the system automatically fills '\0'
printf("%s", ch );
ch is the first address of the array, followed by %s, which means that the output starts from this address and ends with '\0'
Notice
The array name represents the starting address of the array. It should not be &, &ch is wrong, it is OK &ch[0]
You can input and output from the middle of the array
scanf("%s", &ch[3] ); printf("%s", ch );
String processing functions
String output function
puts( ch);
ch can be a character array name
Character pointer
String constants
The difference from %s
Automatically wrap the line after puts output
String input function
gets(ch);
ch can be a character array name
Character pointer (exact pointer)
gets(s1,s2); wrong
Difference from %s input
gets can only end with return
String processing function string.h
String link strcat(character array 1, string 2)
The former must be a variable, and the space size can put the sum of the two characters.
The latter, constant variables are available
Only '\0' in the latter result is retained
practise
String copy strcpy (character array 1, string 2)
The former must be a variable, and the space size can put the sum of the two characters.
The latter, constant variables are available
The result is that the content before character 2, '\0' is copied into the character array, and '\0' is also copied together.
practise
strncpy( str1, str2, n )
Copy the first n characters in str2 to str1
Don't copy '\0'
string comparison strcmp( string 1, string 2)
All constant variables are possible
Order: Compare ASCII values of characters one by one from left to right
End: Encounter '\0', or different characters
Result: 0 means equality, 1>2 positive value 1, 1<2 negative value -1
Determine whether a string is equal
if( strcmp(s1,s2)==0 ) ;
string length strlen (string)
Find the length of the actual string, excluding '\0'
Number of characters before the first '\0'
practise
Convert lowercase strlwr(string)
Convert capital strupr(string)
practise
Delete special characters in strings
String copy
String comparison
String connection
Statistics the number of words
Count the number of times a substring appears in the main string
Use the filtering method to find prime numbers within 100
Insert, delete
function
Overview
Definition: A program that can complete a specific function
Notice
Compilation unit: file
Compile in source programs
The execution of C starts with the main function
All functions are parallel, that is, the function definitions are independent of each other.
Definitions cannot be nested
Functions can be called mutually, and main functions cannot be called.
Function calls can be nested
Classification
User perspective
User functions
User-defined to solve specialized problems
System functions
Standard function, scanf
Functions' own form
There are parameter functions
sqrt(n)
No tragic function
getchar()
The angle of return value
There is a return value
strcmp(s1,s2); pow(x,y);
No return value
Angle of range of action
External functions
Internal functions
Function definition
Definition format with parameter functions
Definition format of non-parameter function
Empty function
dummy(){ }
Function parameters and function values
parameter
Formal parameters
Define functions, in brackets
Redirected
Actual argument
Calling functions to use parameters
Main tune
illustrate
When defining a function, you must specify the type of the formal parameter
Format: Data type Formal parameter name
The actual argument can be a constant, a variable, or an expression, but it must have an exact value.
Allocation and release of formal parameter storage units
Allocate during call, copy the value of the actual parameter to the formal parameter, and release it after the call
The real parameter is passed to the one-way value of the formal parameter. The real parameter is assigned different storage units. Modifying the formal parameter does not affect the actual parameter.
The return value of the function
The return value of the function is obtained through the return statement
The number of return statements, multiple, to which one is executed, which one works
The brackets after the return statement can be omitted, and can be constants, variables, and expressions require exact values.
Type of function value
The type of function return value
Determined at the time of definition
The function type is inconsistent with the type returned by the return statement
The function type determines the type of return value
There is no return statement in the function
Returns an uncertain value unless defined as void
No return value is required, defined as void
Return can still be used, but there cannot be a value afterwards
The default return value type of function is int
Calling of functions
General format
Function name (real parameter table column);
Comma interval between multiple parameters
The number, order, and type of parameters (assignment compatible) are consistent
Call method
Function statements
printf("OK");
Function expressions
x = 10 * sqrt(y);
Function parameters
max( max( x, y ), z );
Calling process
Registration of formal parameters is allocated to storage unit, real parameter value Assign to formal parameters
Practical parameters -》Formal parameters One-way value transfer
When multiple functions are called in nested, follow the first call and then return.
End of return statement, or close braces }
Declaration of the called function and function prototype
Call another function, meet the conditions
The called function must exist (i.e., the defined function)
Library functions
scanf
Custom functions
max(x, y )
Using library functions
Use #include at the beginning of the file to include the corresponding header file
stdio.h
math.h
abs(), fabs(), pow(), sin()
string.h
strcpy(), strcat(), strcmp()
strlen()
ctype.h
malloc.h(stdlib.h)
malloc(),free(), calloc()
Custom functions
Declare the called function
The difference between definition and declaration
significance
Function type Function name, formal parameter table column and a complete function body Definition is the establishment of function functions
Perform a defined (existent) function
Number of
The same name, in a file, there is only one
Multiple
Location
Function definitions cannot be nested
Which function is called, where is declared?
Scope
Internal function (this file), external function (other file)
Declare its function Declare its file
Function prototype
Function declarations in C language are called function prototypes
Function type Function name (parameter type 1, formal parameter 1, parameter type 2, formal parameter 2...)
Function type Function name (parameter type 1, parameter type 2...)
The following situations are not required to be declared
Defined first, call back
Before all function definitions, the function at the beginning of the file has been declared outside the function. No need to declare each main call function.
The return value of the function is int without declaration
Nested calls to functions
Call another function
e = 1 1/1! 1/2! 1/3! … 1/n!
double fun( int n ) calculates the factorial of n
double e( int n ) calculates n terms sum
void main()
Recursive call to functions
Direct recursion, indirect recursion
Similar to nested calls of functions, except that each time the same function is called
Conditions that can be implemented recursively
Initial situation (termination condition), such as: n<=1
Situation n can be described by situation n-1, for example: n! = n * (n-1)!
Note: Test first, then recursion. Recursion is conditional. Only when the conditions are met can you be recursive.
practise
Normal problem solving
Reverse the result from the termination condition
Copy 3 times
evaluate
Recursion can be converted to non-recursion
The recursive implementation uses the stack
Array as function parameters
Array elements make actual parameters
Same level as variable
Value pass
Array name as function parameters
Array name, address constant
Pass the address
Note
Definition: Arrays should be declared separately in the main and called functions
Type: Consistent
Size: The size of the shape parameter group and the real parameter group can be different. The shape parameter group can not specify the size. Suppose another parameter passes the number of elements void fun( int array[], int n )
The array name is used as a real parameter, instead of passing the value of the array to the shape parameter group, the starting address of the real parameter group to the shape parameter group. The shape parameter group and the real parameter group occupy the same storage unit. The elements in the shape parameter group change, and the image real parameter group
Multidimensional arrays make function parameters
Actual argument, use array name
Formal parameters, the size of each dimension can be specified, and the size of the first dimension can be omitted.
practise
Sort the first n elements in a one-dimensional array
Save the row number of the smallest element of each column in a two-dimensional array in a one-dimensional array
Local and global variables
Local variables
Location
Inside the function
In compound statement
Scope
Functions that define it
Compound statement that defines it
Survival period
Allocation of storage units when called, release at the end (except static)
illustrate
Variables defined in main function are only valid in mian function
Different functions can define variables with the same name, represent different objects, occupy different storage units in memory, and do not interfere with each other.
Formal parameters are also local variables
Global variables
Location
Outside the function
Scope
From definition to end of file declaration, declare its function
Survival period
Static storage area, until the program runs, it always takes up memory and does not release it
illustrate
Function: Increase communication channels between functions
It is recommended to use less
Survival period
General
readability
Any function can be modified, it is difficult to determine the value of a variable at a certain moment.
In a source file, the global variable is the same as the local variable
Global variables do not work within the scope of local variables
Take the nearest principle
Storage category of variables
Scope, life span
Variable and function properties
Data Type
Storage category
How to store in memory
Static storage
Dynamic storage
auto variables
When local variables in a function are not specifically declared, the default auto is
Allocate in dynamic storage area, and allocation and release are determined by the system
Scope
Functions that define it
Survival period
Allocate on call, end release
Features
The system cannot be initialized, and each call requires manual initial value
Local invariant declared by static
The call ends, the storage unit is not released, and the value of the last call ends
Scope
Same as local variables
Survival period
Always take up memory and not release
Features
The system automatically assigns initial values, or can manually assign initial values, and the initialization is only done once.
Keep the value at the end of the last call
register register variable
register int i, j=10;
Features
Local automatic variables and formal parameters, global variables are not
The number of registers is limited, so you cannot define too many
register static int a = 10; wrong
Declare external variables with extern
Declare external variables in file
Extend the scope of global variables
Location
In the function using it
Start of the file
extern int a, b;
extern a, b;
Declare external variables in programs with multiple files
One file refers to global variables in another file
Location
Start of the file
Static storage area
Global variables, local variables declared by static
The system can automatically assign initial values, or manually assign initial values.
Dynamic storage area
Local variables (no static)
Formal parameters
Manually assign initial value every time
Internal and external functions
Internal function (static function)
Functions that can only be called by other functions in this file
Add static before function name and function type when defining
static int fun( int a, int b ){}
External functions
When defining, the extern is first crowned, indicating the external function
Functions are implicitly external functions
extern int fun( int x, inty ){}
pointer
Overview
Direct access
By variable name
Indirect access
Relationships pointed by pointers
A variable that stores the address points to a normal variable
The variable that stores the address is called a pointer variable
Notice
pointer
address
1000
Pointer variable
Variables that store address
p
Pointer variable
definition
Base type * pointer variable name;
int *p;
When defining, * does not do any operation, which means that p is followed by it is a pointer variable, and p points to int, that is, p can store the address of the int variable
p is a pointer variable, and the address is stored in the variable p, not *p
Operation
Assignment
Take the address of the variable
int x, *p; p = &x;
Get the first address of the array
int a[10], *p; p = a; or p = &a[0];
Pointer variables assign each other
int x, *p1, *p2; p1 = &x; p2 = p1;
The types pointed to by p1 and p2 must be the same. When assigning values, the pointer variable on the right has an exact pointing point.
Application space return address
int *p; p = (int *)malloc( sizeof( int ) );
Contains malloc.h
Assign NULL value
int *p; p = NULL; p = 0; p = '\0'
Make p pointing empty to prevent misuse
initialization
Storage category Base type *Pointer variable name = Address;
int x, *p = &x;
Arithmetic operations
Pointer variable points to a continuous memory unit. It can complete addition and subtraction, self-increase and self-decrease operations with int.
int a[10]; p1=p2-1; Think of the addition and subtraction operations of characters int *p1, *p2; p2=p1 3; p1 = a; p2-p1; p2 = a 1;
p1 p2 meaningless
Relational operations
A continuous space
Notice
int *p; p is a pointer variable, not *p
Pointer variables can only point to variables of the same type
Address operator and pointer operator
&
The operation object must be a defined variable or array element.
The calculation result is the first address of the variable in memory
&3, &(x y), register variable Error
*
The operation object, the pointer that has been assigned, the address
Function: Take the content of the unit pointed to by the given address
* and & operations are inverse operations
The priority is the same, right-hand combination
*&a => *(&a) => *(1000) => *pa => a
&*pa => &(*pa) => &(a) => 1000 => pa
&*a => a
Note: & variables, * address
Pointer variables can only store addresses
Pointer variables as function parameters
Pointer variables are used as function parameters and pass address
During the execution of the function, the value of the variable pointed to by the pointer variable changes.
Pointer and one-dimensional array
The address of the variable
The first address of the array: the starting address, the array name
Pointer variable to array elements
int a[10]; int *p; p = a; or p = &a[0];
Reference array elements through pointer variables
p=a; a[i]<=>*(a i), bracket index operator p = a 3; p[5] = ? a[8] a: array name, address constant, a cannot be modified. Error p: pointer variable, p can be modified
The address of the i-th element&a[i]
p i
ai
Sub-theme 4
The value of the i-th element a[i]
*(p i)
*(a i)
Pointer method
Pointers to one-dimensional arrays can also be subscripted
p[i]
a[i]
Subscript method