当前位置:网站首页>3W word will help you master the C language as soon as you get started - the latest update is up to 5.22
3W word will help you master the C language as soon as you get started - the latest update is up to 5.22
2022-07-04 10:55:00 【Eric%258436】
** If there is a mistake , Thank you for correcting **
If there is a mistake , Thank you for correcting , Please send a private message to the blogger , There is a red envelope for hard work , Worship “ one-word teacher ”.
Please find the paragraphs you need according to the table of contents
Read more manuals !!!
The process of writing code
To write : The process of programmers writing code Let programmers understand (.c)
compiler : Check the syntax errors of the code , Generate assembly language .(.obj)
Assembler : Assembly language to be generated Generate binary languages ( Target file )
The connector : Will generate good Binary language + The library used + Startup code ====》 Executable file .exe
Hexadecimal conversion : This article will not explain .
Binary system octal Decimal system Hexadecimal Are all integer output forms Different bases It's just a representation of data The data itself will not be modified
Binary system 0-1
octal 0-7
Decimal system 0-9
Hexadecimal 0-9 A-F
Some small applications
%p Output address
%d Decimal integer output A signed int Data output
%o octal
%x Hexadecimal
%ld A signed long Integer data output
%lu Unsigned long Integer data output
%hd A signed short Data output
%hu Unsigned short Data output
%c Character output Single character
%s Is the output string
%f Output float data scanf(“%f”, &f);
%lf Output double data scanf(“%lf”, &d);
%u Unsigned integer output %p Pointer value
Special representation of floating point numbers
%5d Indicated occupation 5 The terminal bit widths are aligned to the right
%-5d Indicated occupation 5 The terminal bit widths are aligned to the left
%05d Indicates five bit width right aligned , Empty complement 0 // %-05d You can't write it like that It doesn't work There will be ambiguity
%5.2f 5 Indicates the total bit width .2 Indicates that the decimal places are reserved 2 position
%.2f Express Keep two decimal places after the decimal point
Use anything , Keywords that must exist first
Data type key 12 individual char short int long float double unsigned signed struct union enum void
Control statement keywords 12 individual if else switch case default for do while break continue goto return
keyword 4 individual auto extern register static const
Other keywords 3 individual sizeof typedef volatile
Reserved words are not recorded
Reasons for distinguishing keywords
Allocate reasonable space for users
A byte bit=8b Bit binary 0000 0000 — 1111 1111 1KB=1024B (1MB 1GB 1TB 1EB)
32 Bit platform
char Character 1 Bytes short Short 2 Bytes int integer 4 Bytes long Long integer 4 Bytes
long long Some support Some don't support 8 byte float Single precision floating point Four bytes
double Double precision floating point 8 byte
Case study Verify data type length sizeof: Measure the length of the type
sizeof There are three grammatical forms , as follows :
- sizeof( object ); // sizeof( object );
- sizeof( type_name ); // sizeof( type );
- sizeof object; // sizeof object ;
#include <stdio.h>
void main(){
void main() {
int a;
short char b;
unsigned u;
char e,f,g;
long int c;
e = sizeof(a);//b,c,u,e
printf("sizeof(a)=%d",e);
f = sizeof(int);
printf("sizeof(int)=%d",f);
g = sizeof int;
printf("g=%d",g);
printf("sizeof int=%d",sizeof(int));
}
64 Bit platform
long Type occupation 8 byte Everything else is the same
unsigned An unsigned number Data has no sign bit All binary bits of itself are data bits
signed Signed number Default general omission The highest bit of binary is the sign bit Other bits are data bits . The highest bit is 1 A negative number 0 It means a positive number
signed char Range 1111 1111 -1000 0000 ~ 0000 0000 -0111 1111 /-10 == 1000 1010
Structure struct And the public union
struct Members in the structure have independent spaces
union Members in the community Share the same space
enum enumeration List the variables and the values to be assigned one by one
enum BOOL {false,true};
enum BOOL bool = false;
void No type ( important )
Out-of-service void Defining variables
auto Automatic type /c Low status in c++ Useful
register Register variables If there is no surface register But it is frequently used The system will also put it into the register
static Static variables
const A read-only variable
sizeof Measure the type and size
typedef Is an existing type Rename it
volatile Prevent compiler optimization
Constants and variables
1. Why do I need variables ?
Variables are the basic units of program composition
Explanation of variables Equivalent to the representation of a data storage variable in memory
Constant The defined value cannot be modified ( You can't say the opposite ) integer Real type String type Character
Real constant 123e3 e Represents the power
Don't to f At the end of the Real constant by double type float f=3.14f
With f At the end of the Real constant by float type
character constants
Direct constants Enclosed in single quotation marks ‘a’ ‘d’ The characters stored in the calculator are ASCII value
char ch =‘a’ Essentially what's stored is ‘a’ Of ASCII value
Escape character \ Start character \n Line break \t tab tabs \ Output \ \0 ==》 0 “0” Address number of string But these two stores are the same
Fu 0 Standard way c=’\0’
str %d ASCII value %c str In itself String as type Represents the space occupied by the string As address representative str The first address
The system will automatically add a \0 namely “a” Include ‘a’ and ‘\0’
‘ ’ Take the string ASCII value “” Get the address of the first element
%s Start with the first element Output one by one \0 End output
notes : Here str It refers to the definition such as char str=abc; Not str data type
Variable The system depends on the type of variable Open up corresponding space Values can be modified The variable name represents the content of the space The operation variable is the operation of spatial content First Statement =》 To assign a value =》 After use
1. Variables represent a storage area of memory ( Different data types , Different occupation sizes )
2. This area must have its own variable name and type
3. Variables must be declared before using
4. Variables cannot have the same name in the same scope
5. The data in this area can change constantly in the same range
6. Three elements of variable ( Variable name + value + data type )
7. Different compiler versions have different requirements for variable definitions ,c89 The variable is required to be defined before the statement
Naming rules for variable names Cannot start with a number Consisting of alphanumeric underscores
1. Keywords are not allowed
2. All macro definitions , Enumeration constant , Constant ( A read-only variable ) Use all capital letters _ Split words
3. Don't forget to initialize when defining variables
4. Variable name , Method / function name : Little hump Hump
data type
/* For an in-depth understanding, please see the development manuals of different systems , Not the same , It is too closely related to the underlying hardware , Different hardware is different ,linux Follow win It's a big difference Basic types value type The default is signed signed and unsigned Size should be in range , Do not overflow , Own Baidu range , Different systems are different , The out of range value will change integer short int long Don't use it until you can't fit it long long And so on For output %lld floating-point float double Character type char C89 No definition Boolean 0 Express False Not 0 Express True Construction type Array arr Structure struct Consortium union Enumeration type enum Pointer types Empty type void PS:1.C Not in the language string Replace 2. The number of bytes of the same data type may be different in different bit systems ( Such as :int To baidu ) */
floating-point
floating-point Two ways of writing
1. Decimal system float=3.2
2. Scientific enumeration float=5.12e2(-2) // e To what power
Use a higher precision value It is recommended to use double
char type
ASCII Introduce
Operation of integer variables 【 read 、 Write 】 ==》 assignment / Value - operation
local variable Not initialized Random content
scanf(“%d”,&data); &data Representative is data The starting address of the corresponding space Only one character can be extracted scanf(“%c”,&ch)
ch = getchar() Get a character
typedef Re Take an alias
1. Use existing types Define a variable
2. Use alias Replace Variable name
3. Add typedef
const sketch
Grammatical structure :const data type Constant names = Constant values ;
const keyword
Modifying variables Role is Read only cannot be modified
Scope of action This document is global From the end of the statement But not across files If you want to cross files need extern
however If you know the address, you can modify it indirectly Not through variable names
const int p
const stay On the left Express cosnt Modification is * instead of p
effect : Users cannot use *p Change space content however p It can point to other spaces (*p read-only p Can read but write )
int const p;*
const stay On the right Express const Modification is p
user Can pass p modify p The space content pointed to But you can't change p The direction of (*p Can read but write p read-only )
*const int *const p;(p p It's all read-only )
define Macro definition
#define name value
Let me write it first , As a replacement
define and const difference
1.const When defining constants , Belt type ;define Without type
2.const Is compiled , It works when it's running ; and define It works in the preprocessing phase of compilation
3.define It's just a simple replacement , There is no type check , Simple string substitution can lead to boundary effects ( If you want to treat the back as a whole, you have to add parentheses )
4.const Variables can be debugged ,define It is impossible to debug ( The compilation phase has been replaced , There is no it when debugging )
5.const Cannot redefine , You cannot define two identical constants ; and define Can pass undef To cancel the definition of a symbol , Redefine
6.define Can combine #ifdef,#ifndef and #endif To use , Make the code more flexible
Data type conversion
Automatic conversion Types that occupy less memory are converted to types that occupy more memory / From low precision to high precision
Data precision size sorting self Baidu query
When signed and unsigned participate in the calculation Will turn signed into unsigned ( Complement code ) A large number
int and double Together, we will put int turn double
char and short transformation because char short The number of bytes is small It's easy to overflow and turn automatically int Prevent data loss
Cast : High precision to low precision
( Type specifier )( expression ) / Just a temporary conversion The current statement is valid It doesn't affect the original value , Returns the new value
It's not round Direct truncation
chestnuts :
float x = 3.94f;
int j =0;
j = (int)x; //3
Only valid for the latest number Want to use more ()
int num2=(int)(10.655.1+62.3)
int num3=(int)10.256545+564.34
Operator
Arithmetic operator + - * / % ++ -- The sign
Assignment operator = += -= *= /= <<= >>= &= |=
Relational operator ( Comparison operator ) > < >= <= != ==
Logical operators && || !
An operator << >> & | ^ ~
Ternary operator expression ? expression 1 : expression 2
1. Arithmetic operator + - * / integer %
/ integer a/b ab When it's positive integer division “%f\n”,5/2.0f
% Remainder
a % b = a - a / b *b
Arithmetic operation may result in data loss , Such as :int 10/3=3 and float=3.333333~, Improve data accuracy to solve
++ – Operator ++i --i Calculate first and then value i-- i++ Value first and then calculate
2. Relational operator > < == >= <= !=
3. Logical operators ! && || Pay attention to the short circuit
! Logic is not 0 For false Everything else is true
Short circuit phenomenon && A false full holiday If it is false, it will not be executed
|| True truth If it is true, it will no longer be implemented
4. An operator << >> & | ~ ^
& Bitwise AND grammar whole 1 by 1 For the other 0 and 1 meet remain unchanged and 0 meet Zero clearing // The bottom floor is cleared
| Press bit or grammar Yes 1 be 1 whole 0 by 0 and 0 Phase or remain unchanged and 1 Phase or Set up 1 // Fix it in place 1
~ According to the not grammar 0 change 1 1 change 0 coordination & | operation
^ Bitwise XOR grammar grammar Same as 0 Different for 1 And 0 XOR remains unchanged and 1 XOR negates // The fixed bit High and low frequency reversals occur
Such as :
1010 1010
0000 1111
-----------
1010 0101
Shift left operator << Throw away more Make up for less 0 Move digits Don't exceed your own length
Shift right operator >> Overflow discard
Logical shift right : On the right side of the discarded Left padding
Count right : Unsigned numbers are discarded on the right Left padding
Signed number :
Positive numbers On the right side of the discarded Left complement 0
negative On the right side of the discarded Left complement 1
Logical right shift and arithmetic right shift It's the compiler that decides But we can detect
data = data & ~(0x01 << 5 | 0x01 <<1); Reset operation No, ~ Yes, it is 1
5. Assignment operator (= And its extended assignment operator )
(a +=b )==( a = a + b)
6. Ternary operator (?:)
Master Yizhen / The conditional expression is 1( really ) expression 1 perform
Can be converted to if-else sentence
7. The comma operator (,) The lowest priority
8. Pointer operator (* and &)
9. Find byte operator (sizeof( Variable or constant ))
10. Cast operators (( Variable or constant ))
11. Component operators (.->)
12. Subscript operator (【】)
13. other ( Such as function call operator ();)
priority : Priority first , Different priorities look at the combination Write it yourself and try to add ()
Own Baidu , If you can't remember, put parentheses to improve your priority , There's no need to remember , If you use more, you will
Arithmetic operator > Relational operator > Logical operators ( Except logical non ) > Assignment operator > The comma operator
Middle and same level . higher than * 【】 higher than * function () higher than * == And higher than bit operation and assignment Arithmetic operators are higher than bitwise operators
if sentence
1. Only care about one result of the project choice if
if( expression )
{
sentence 1;
} Expression is true Execute statement / Code block
*if-else sentence If there are two situations that cannot exist at the same time *
if( expression )
{
sentence 1;
}else
{
sentence 2;
} Expression is true Execute statement 1 For false Execute statement 2
*if - else if -else sentence If there are multiple results and they do not appear at the same time *
if( expression 1)
{
sentence 1;
}else if( expression 2)
{
sentence 2;
}else if( expression 3)
{
sentence 3;
}
else // Omission
{
sentence n;
} The expression is almost true Execute a few sentences Which condition is satisfied , Which statement to execute According to the order Meet one and jump out of judgment Don't look at the back
The front is not satisfied with the implementation else The sentence of Every if Statements are independent
switch sentence
switch( expression )
{
case value 1: // It can't be real , character string Only integer values
sentence 1;
break; // Most of them want break A few do not break For example, when the code blocks to be executed are the same in both cases Omit a pair of sentences and break
case value 2: The value can be written || such Don't complain But it may not be consistent with your desired effect
sentence 2;
break;
case value 3:
sentence 3;
break;
case value 4:
sentence 4;
break;
default;// It can be omitted
sentence n;
break;
} With which value Execute which of the following statements break Jump out of If it's all different perform default And then jump out
for loop
for( The initial statement ; The loop condition ; Step condition )
{
Loop statement
}
The initial statement : Execute once at the beginning of the loop // If the variable is initialized in advance It can be omitted
The loop condition : Each cycle must be executed The cycle condition is true Into the loop False exit loop // If you omit Exit must be implemented in a loop statement
Step condition : At the end of each cycle Statement to execute // You can omit it Implement step actions in loop statements Otherwise it's a dead cycle
break You can only jump out of the loop closest to it
continue Launch a single cycle Continue with next cycle
while loop
while( The loop condition )
{
Loop statement ;
} Condition is true Into the circulatory body Execute loop statement
while There are no step statements and initialization statements You need to initialize in advance and write the conditions for exiting the loop
do {
Loop statement
}while( The loop condition ) ;
Execute the loop statement first Then judge the conditions Execute the next cycle for true For false Out of the loop
goto Jump anchor
goto here;
here:
Array
: For convenience Organize several variables of the same type in an orderly form — Become an array
Arrays are of construction data type
According to the elements It is divided into Array of values A character array Pointer array Array of structs
One dimensional numerical array
Definition : demand Please define an array The array has 10 Elements Each element is int
At the time of definition a.arr【】 arr and 【】 The combination is an array
b. Put the determined number of elements into 【】 in
c. Define a common variable with the type of the element
d. Replace as a whole from top to bottom .
int arr【10】;
Array name arr Cannot have the same name as other variable names
The element subscript of the array is from 0 Start :0-9
The elements of the array are :arr【0】、arr【1】~arr【9】 Access array 【10】 Transboundary
The elements of an array are equivalent to ordinary variables
When defining an array ,【】 The value of the inside It can't be a variable .
If the local array is not initialized Uncertain content
initialization The action of assigning values to variables or array elements during definition is called initialization
All initialization int arr=【5】={1,2,3,4,5}
Partial initialization Not initialized Partial automatic supplement 0
Initialization operations common operations Clear all elements of the array int arr【5】={0} // Value initialization arr【0】=0 Other zero filling
int arr【5】={2} // 2 0 0 0 0
Expand : initialization int arr【5】={【2】=3,【4】=7}
The memory size of the array Rely on the content to open up = Number of elements * The size of each element
Important int n= sizeof(arr)/sizeof(arr[0]) Get the number of array elements in general
Two dimensional array int arr[n][n];
Two dimensional array initialization Segment initialization int arr【3】【4】={ {1,2,3,4},{5,6,7,8},{9,10,11,12}}
Continuous initialization : Fill a row To put down a line int arr 【3】【4】={1,2,3,4,5,6,7,8,9,10,11,12}
A character array char arr[];
initialization char str=[‘h’,‘l’,‘l’] Initialize one by one Not recommended
char str[6]=“hello”; In the form of strings initialization recommend
Traverse One by one Not recommended printf(“%c”,st[i])
Global traversal recommend printf(“%s\n”,str)
important : The name of a one-dimensional array represents the... Of the array 0 Addresses of elements , You must remember
The difference between character by character initialization and overall initialization
one by one How much is how much The system will not consider it str
whole Finally, there will be \0 The system thinks that str
scanf and %s When you use it , There is a drawback , If a space is encountered, the input will end
gets(buf); Get the string with spaces shortcoming : When getting keyboard input I don't care buf Size , Easy to cause memory pollution
fgets function You can get the string with spaces , It can also guarantee buf Don't cross the border
> char *fgets(char *s , int size ,FILE *stream) s Represents the spatial address where the string is stored size
> The maximum length of the string that can be extracted size-1 The last deposit \0 stream stdin Indicates standard input device Return value Get the address of the first element of the string
> char buf[10] = "";
printf("shuru")
fgets(buf,sizeof(buf),stdin);
printf("buf=%s\n",buf); Package into a function
> ASCII Lowercase to uppercase -32
Two dimensional character array char str[2][6]={"","",""};
Whether it's a two-dimensional array of numbers or characters , At initialization time , Line marks can be omitted ( The first parameter ) The number of rows is determined by the specific initialization
The second parameter is the row size
Library function
Custom function
Function type Function name ( parameter types Parameter name )
{
Data definition part ;
Execute statement part ;
} Function type : Function return value type Default int type
Function definition : Realize the function function 、 Determine the body of the function 、 return type 、 parameter types . Let the function exist Function declaration : Not to implement functions Only the return value type of the function 、 parameter types 、 Function name
Function call : Execution of a function
Function definition
return type Function name ( parameter types Shape parameter ){
The body of the function ;
}
return type : The type of the future return value of the function
Function name : Function's entry address
Shape parameter : Function external data Pass on to intra-function bridge
The body of the function : Specific function belts
Function declaration : return type Function name ( parameter types Shape parameter ) Tell compiler Functions exist Please compile
Function call : Function name ( Actual parameters );
Actual parameters : Actual data outside the function
return;1. Return function structure 2. End function rigorous
If you don't write anything about the formal parameters of a function You can write arguments when calling , It's just that the arguments can't be used Reading is misleading Function parameter If the function has no arguments Write the formal parameter as void Advanced Editor
You will not be allowed to pass parameters when calling A low-level write parameter does not report an error But don't write
Parameter passing Function calls make room for formal parameters
register EA have return Return value
! Be careful
The formal parameter of the function It is essentially a local variable of a function
Shape parameter There is no space for function definition The space is opened only when the function is called
Shape parameter At the end of the function To be released
Function return value <=4 byte There are registers >4 byte There is a stack area
Storage category of variables
extern Declare externally available trouble zhu.h .h It will automatically add #include “zhu.h”
Header file idea header file
Ordinary local variables
Static local variables
General global variables
Static global variables
Memory partition
Executable is not running
bss paragraph Global uninitialized data Global area
data paragraph Global initialization data Global area
text paragraph Code segment Code section
Run the executable // When we talk about pointers later , There is an in-depth explanation of memory
Heap area ---- Can read but write Use malloc calloc realloc free Dynamic applications
The stack area ---- Can read but write Local structure Function parameter
Function return value >4 byte <4 Bytes in register Global area — Can read but write Global variables Static variables static
Text constant area – read-only String constant Symbolic constant
Code section — read-only Binary code
Ordinary local variables
Definition form : stay {( Compound statement )} Ordinary variables defined inside Ordinary variables
Scope of action : The nearest to it {} Effective in
Life cycle : The nearest to it {} In between , Leave {} Local variables of The system automatically recycles
Storage area : The stack area ( Stack characteristics : First in, then out Bucket type )
General global variables
Definition form : A variable defined outside a function Common global variables {( Compound statement )} Outside
Scope of action :a. Current source files are valid
If not assigned Add extern It's easy to treat it as a definition without assignment It is easy to read
b. When other source files use global variables Must use extern Statement
Life cycle : The whole process is effective ( At the end of the program Global variables are released )
Storage area : Global area
Be careful :A. Global variables are not initialized The content is 0 In the global area bss paragraph , Will be automatically supplemented 0
B. If the global variable To use... In other source files , Must be in use yuanwej To add extern Statement
C. If the global and local names are the same Local variables are preferred
Static local variables
Definition form : stay {} In the definition of It must be preceded by staic Variables that modify this are called static local variables
Scope of action : The nearest to it {} In between
Life cycle : The whole process ( At the end of the program Static local variables are released )
Storage area : Global area ( The life cycle of the global area is the whole process )
Be careful :A. Static local variables are not initialized , The content is 0
B. Can only be defined once , Space will not be released ( important )
Static global variables
Definition form : Define... Outside the function At the same time, add static Such a variable is Static global variables
Scope of action : The current source file is valid Cannot be used in other source files // benefits There is no conflict in different files , Repeat without error
Life cycle : The whole process ( Program end Static global variables are released )
Storage area : Global area
matters needing attention :A. Static global variables are not initialized The content is 0
B. Static global variables are only valid in the current source file
Global function ( Ordinary function )
characteristic : Other source files can use global functions But it must be added extern Statement
Static functions ( Local function ) The return value is preceded by static void ming(can){}
characteristic : Can only be used in the current source file , Cannot be used in other source files
If you want to call static functions in other source files You need to encapsulate static functions in global functions At the same time, the global function and static function must be the same source file
C Language compilation process (gcc)
// The integrated development environment cannot see the compilation process
Preprocessing : The header file contains , Macro replace , Conditional compilation , Delete Note , No grammar check
compile : The preprocessed file Generate Assembly files Syntax check
assembly : The assembly file compile Binary
link : Put a lot of binary files + library + Startup code Generate Executable file
summary One step in place compile :gcc Source file -o Executable file
Preprocessing :
1. File contains #include <> ,""
<hehe.h> Search from the specified directory of the system hehe.h // Header file used to contain the system
“hehe.h” Start with the source file Find the directory where If you can't find it Then go to the directory specified by the system to find // Users include User defined header file
Be careful Never include name .c Although not wrong It's easy to make a mistake Repetition contains many definitions Will make mistakes
2. Macro definition : #define Macro name character string
Don't add ; There are too many replacements ; There will be grammatical errors The replacement action is called Macro expansion
Macro definitions only work in the current file
Macros without parameters
Macro with parameters
call #define Macro name ( Parameters 1, Parameters 2…) character string
Macro general size Distinguish from ordinary functions
Macro parameters a b Cannot write type
call : Macro name ( Parameters )
define MY_HONG(a,b) ab There is no guarantee of integrity
define MY_HONG(a,b) ((a)(b)) Guarantee integrity
Macro expansion : The essence Just replace No grammar check
It will expand as many times as it is called There is no function call procedure in the execution process , There is no need for functions to go in and out of the stack , So macros with parameters Waste space Save time
Surrogate function : There's only one copy of the code , There are code snippets , When calling, read the function instruction from the code segment , When calling, press the stack ( Keep information about function call money ), Stack after calling ( Recover the relevant information before calling the function ), So function is a waste of time , Save time
Terminate the scope of the macro : #undef Macro name
In the macro definition , You can refer to the defined macro name
Conditional compilation : In general , All the lines in the source program are compiled , But sometimes I hope to compile some source program lines only when certain conditions are met , That is, specify the compilation conditions for this part of the source program line .
1. The test exists
#ifdef *** // nothing
sentence 1;// sentence 1
#else // Yes
sentence 2;// sentence 2
#endif
2. The test does not exist
#ifndef ***
sentence 1;
#else
sentence 2;
#endif
3. Judge whether the conditions are true
#if expression
sentence 1
#else
sentence 2
#endif
Prevent header files from repeatedly containing
Mode one :#pragma once The compiler decided Some cannot write , Write one on the first line of all header files Duplicates are automatically filtered
#pragma once Put it in the front of the header file The emphasis is on the file name
Mode two :c/c++ The standard specifies
#ifndef macro A_H Generally, it is consistent with the header file name Name capitalized Replace the dot with an underscore Underlined on both sides
#define macro A_H
The specific content of the header file
#endif ==》 At this time stay main.c Write include<a.h> There will be no repetition of definitions
#ifdef The emphasis is on content Not the file
Positive numbers | negative | remarks | |||
---|---|---|---|---|---|
Concept | 10 | Concept | -10 | With 1 Byte as an example | |
Original code | Binary form of data | 0000 1010 | Binary form of original code data | 10001010 | 1000 1010 |
Inverse code | It's the original code | 0000 1010 | Inverse code The sign bit of the source code remains unchanged , Reverse other bits | 1111 0101 | |
Complement code | It's complement | 0000 1010 | Complement code Inverse code +1 | 1111 0110 |
Be careful : An unsigned number , Positive numbers , Their original code == Inverse code == Complement code
And negative numbers :
Inverse code = The sign bit of the original code remains unchanged, and other bits are reversed
Complement code = Inverse code +1
important ! negative ( Any data , Positive numbers and unsigned numbers are only the same as the original complement ) All stored in the computer are complements
Why should computers complement ?
Change subtraction to addition No mistakes
In order to expand the scope of data representation -0 regard as -128 therefore The signed number range of a byte is -128-127
An unsigned number 0-255
Signed and unsigned numbers The width does not change Just the scope has changed
summary : The meaning of the complement
1. Unified 0 The coding +0 -0 All the complements are 0000 0000
2. Subtract Variation and addition
The storage and reading of data by computer
Storage :
Signed number
negative Complement Storage ( Positive numbers are also It's just that the complement code is the same as the original code )
Hexadecimal Positive numbers Store in original code
octal ( Every three bits Represents one octal ): Store in original code
The situation of crossing the border : Store in original code // It is not recommended that the stored value is out of bounds
An unsigned number Before the assignment action Complete the storage action I don't know if it has symbols unsigned char data= -10 ==》0000 1010
Read : Unsigned take %x %u %o %lu Output the original data of memory
General choice %x Hexadecimal convenient Every four bits of binary represents one hexadecimal
Signed access %d %hd %ld
First, look at the highest bit of memory
If the highest position is 1 The data in memory is the complement of a certain number The sign bits remain the same Take the opposite +1 Calculate the original code
If the highest position is 0 Output the data as it is
Value passing and address passing
Value passed : Other types
Address delivery : Pointer type and array type
The pointer
Want to learn pointer well You must understand the memory
Memory meaning
Memory : In the composition of the computer , Used to store programs and data , auxiliary CPU An important part of arithmetic processing
External memory is also called external memory , Long term storage of data , Power down without losing data . Common external storage devices : Hard disk ,flash,rom,U disc , Compact disc , Magnetic tape
Memory is also called internal memory , Temporarily store data , Power down, data loss . Common memory devices :ram、ddr( Related to pointer )
Memory is communication cpu Bridge with hard disk ; To store temporarily cpu Operation data in ; Temporary storage of data exchanged with external storage Physical memory : Real storage devices ( Generally, it is not allowed to operate )
Virtual memory : The memory virtualized by the operating system ( We need to operate ) The operating system maps between physical memory and virtual memory
stay 32 A system. , Each process ( Running programs ) The addressing range is 4G,0x00 00 00 00 ~ 0xff ff ff ff ff (64 Empathy )
Writing an application , All we see are virtual addresses .
When running the program , The operating system partitions the virtual memory
1. Pile up : When dynamically applying for memory , Open up memory in the heap
2. Stack : It mainly stores local variables ( Inside the function , Or variables defined inside a compound statement ).
3. Static global area
( 1): Uninitialized static global area : Static variables ( When defining , Add in front static modification ), Or global variables , There is no initialization in this area
( 2): Initialized static global area : Global variables , Static variables , Assigned an initial value , This zone exists
4. Code section : Store our program code
5. Text constant area : To store constants .
Memory stores data in bytes , We can put the virtual addressing space in the program , As a large one-dimensional character array
Memory address overview
The operating system assigns a number to each storage unit , from 0x00 00 00 00 ~ 0xff ff ff ff
This number We call it address
The pointer is the address
Pointer to the variable : It's a variable , It's a pointer variable , That is, this variable is used to store an address number ( The essence is a variable , Only the variable stores the memory address number ( Address / The pointer ))
stay 32 Under the platform , The address bus is 32 Bit , So the address is 32 Bit number , So the pointer variable is 32 Bit namely 4 Bytes
stay 32 Under the platform , Any type of address number is 4 byte
Defining pointer variables ( important )
To define a pointer variable :
1.* Modify pointer variable name *p
2. Keep the address of the variable of what type Just use this type to define a common variable int a
2. From the top down Whole replacement
int num = 10;
int *p ; Express p Is a pointer variable
p= # establish p And num The relationship between p preservation num Starting position ( The first address )
The use of pointer variables // adopt p For the saved address space Read and write
In the use of :p: It means take p Saved address number Corresponding space content ( Yes p operation == Yes num operation ) Pointer to the variable p To quote
scanf(“%d”,p);== Yes num assignment ( if &p It means that the keyboard is given p assignment , instead of num)
*p How to take it out 10 Of By p Decisive And num No problem num Just tell the address How much How long does it take from p decision
#include <stdio.h>
void main() {
int num = 8;
int* ptr = #
printf("num Value =%d,num The address of =%p\n",num,&num);
printf("ptr The address of =%p\n", &ptr);
*ptr = 99;
printf("num Value =%d\n", *ptr);
printf("ptr Ground value of =%p\n", &ptr);
// First level pointer
int* ptr1 = ptr;
*ptr1 = 25;
printf("ptr1=%d", *ptr1);
}
Pointer variable type
In the definition :
Pointer to the variable Self type . Drag the pointer variable name Black What type is left The pointer variable itself is of what type
p Its own type is int * .
Pointer to the variable The type pointed to . Match the pointer variable name with the nearest one * Drag black together What type is left Pointer variables point to what type
p The type of direction is int ==== p keep int The address of a type variable
Point to … type == preservation … The address of a type variable int ** *p;
Point to int **
Multibyte numbers Or they are saving Or reverse deposit Don't have to struggle The system automatically corrects No influence
Pointer variable value width : Determined by the type length pointed to by the pointer variable
Span of pointer variable ( important ): The length of the type pointed to by the pointer variable determines
Cast pointer type // Solve the demand span with different widths ( choice min( span / Width ) Defining pointer variables )
int num = 0x 01020304
char p
p=&num
form :(short*)(p+1)
Initialization of pointer variables
If Local Pointer to the variable Not initialized Keep a random address number ( Never operate )
int p1=null; // Don't want the pointer to point to any address It should be initialized to null ( Never operate )((void)0) Address 0 Operation address is not allowed 0 Protect memory Store the system root file
Initialize the pointer variable to a legal address ( It can take )
int num =10;
int *p2 = #// modification p2 Is a pointer variable ,p2=# Never regard p2 =#
Pointer to the variable p2 The essence It's a variable You can change the point to
p2 = &data; // Change direction
& Fetch address and Pointer dereference ( Take the content of the address pointed to by the pointer ,"" Is to refer to the value of the variable that the pointer points to , A reference is actually the address of the reference variable ,“ Explain ” That is to untie the corresponding thing of the address , Work it out , It's like opening a package , That's the value of the variable , So called “ Quoting ”. Dereference is to return the value saved in the memory address .) difference ( In the use )
num The type is int type
&num The type is int type
If for a variable Address fetch , The type of the entire expression is the type of the variable +
If the The pointer variable takes * The type of the whole expression is The type of pointer variable -*
The address of the pointer &p
Storage address of pointer p
Pointer content *p
Advanced summary : If & and * At the same time Can offset each other . From the right ——> Left ( important )
Precautions for pointers
1.void You can't define variables
void num;// error The system doesn't know num size
2.void * You can define variables
void *p;// Sure p The type is void *, and void Pointer types ,32 Bit platform 4 byte , The system knows to p open up 4 byte
//p It's called the universal pointer p Can keep Any level of pointer
about p Can't be used directly p operation Must realize the right to p Cast of
void test04( )
{
int num = 10;
void *p;
p = #//printf("*p = %d\n",*p);//err because p The pointing type of is void. The system cannot determine the width
printf("*p = %d\n",*(int *)p);//ok p The temporary pointing type is int The system determines the width 4B
}
3. Don't take Not initialized Pointer to the variable take * // because p Not initialized Random content That is to say p To an unknown space The system does not allow users to Value *p operation
4. Don't take Initialize to null The pointer variable of takes *
5. Don't give Pointer to the variable Assign ordinary values // Do not apply for That address number is not a legal space
6. Pointer to the variable Don't operate out of bounds space
Pointer to array element
demand Define a pointer variable , preservation arr Array The first 0 Addresses of elements ( The address of the first element )
int arr【5】={
1,2,3,40}
int *p=null;
p=&arr【0】;
This is the pointer to the array element
p+i: It means the first one i Addresses of elements
*(p+i): It means the first one i The value of the elements
Array of 【】 and () The relationship between * In use 【】 Namely *() abbreviation
Abbreviation rules :+ The value on the left is placed in 【】 Left side + The value on the right is placed in 【】 Inside
Array name arr As a type Represents the total size of the array sizeof(arr)
Array name arr As address Represents the address of the first element ( The first 0 Addresses of elements )
Why? arr On behalf of the 0 Addresses of elements (&arr[0])// It's not the first address
&arr【0】==&*(arr+0)arr+0arr
summary
1.【】 yes *() Abbreviation // It can be simplified later
2. Array name arr Is the address of the first element of the array ( The first 0 Addresses of elements )
arr And &arr The difference between
arr: The address of the first element of the array .+1 Skip an element
&arr: The first address of the array .+1 Skip the entire array
arr and &arr The address number is the same , however The type is completely different
Array name arr It's a symbolic constant . Cannot be assigned .( understand )
The relationship between pointer variables pointing to two elements of the same array
Two pointers to the same array , Pointer variables are subtracted , Returns the number of elements with a difference
Two pointer variables pointing to the same array You can compare the size > < >= <= == !=
Two pointer variables pointing to the same array You can assign
Two pointer variables pointing to the same array Try not to add up .// Transboundary
【】 Inside without crossing the line It could be negative
Pointer array :
The essence is array , It's just that each element of the array is a pointer
Array pointer :
Essence is a pointer , Save the first address of the array
Define a pointer variable Save the first address of the array .+1 Skip the whole arr.( review : How much to adjust depends on the direction )
int arr[5]={10,20,30,40}
int (*p)【5】;
p=&arr;
(p+3)==(arr+3);
Take... For array pointer Get the array element address
&arr With the first address representing the array
((p+0)+3)==*(p【0】+3)==p【0】【3】// * I can't fight Replace with
( Pointer variables pointing to the same array are subtracted to return the number of elements )
2D array name : It represents the address of the first line of the two-dimensional array ,+1 Skip a line
Take the address of the line * Will program The first line of the current line 0 Column address of column
((arr+1)+2)==*(arr【1】+2)==arr【1】【2】
Array pointer And The relationship between two-dimensional arrays
An array of any dimension Physical storage is one-dimensional
Multi level pointer
First level pointer save 0 Level pointer variable ( Common variables ) The address of
2 Level pointer saves level pointer variables ( Common variables ) The address of
…
n Level pointer save n-1 Level pointer variable ( Common variables ) The address of
Pointer as a function parameter
If you want to modify the external value inside the function You need to add the address of the external variable Pass to function ( Take the pointer as the parameter of the function )
Inside the function change p The direction of ( Inside the function to p assignment It has to be delivered p The address of )
One dimensional array name As The parameters of the function
1. If you want to operate on external array elements inside the function Pass the array name of the external array to the function ( important !!!)
arr As a type Represents the total size of the array
arr As address Represents the address of the first element of the array
2. A one-dimensional array as a formal parameter of a function will be optimized to Pointer to the variable
Two dimensional arrays as arguments to functions
1. If you want to operate on external array elements inside the function Pass the array name of the external array to the function ( important !!!)
2. Pointer as function return value
1) Function should not return the address of ordinary local variable
2) A function pointer Is essentially a pointer variable Save the entry address of the function
3) Take * meaningless
Dynamic memory application related concepts
1. In the chapter on arrays , Introduced , The length of the array is predefined , As early as the whole program is fixed ;
2. But in actual programming , This often happens , That is, the required memory space depends on the actual input data , And can't be predetermined
3. In order to solve the above problems ,C The language provides some memory management functions , These memory management functions can dynamically allocate memory space as needed , You can also recycle the memory space that is no longer used
Static and dynamic allocation
Static allocation
1. In the process of compiling or running a program , The allocation of memory space according to a predetermined size
2. You must know the size of the required space in advance
3. Allocated in stack area or global variable area , Usually in the form of an array
4. Allocate... As planned
Dynamic allocation
1. While the program is running , Freely allocate the required space according to the required size
2. Distribute on demand
3. Assigned in the heap area , Generally, specific functions are used for allocation
Dynamic memory application related functions
1.malloc Allocate memory space function
The function prototype :void malloc (unsigned int num_bytes);
Call form :( Type specifier )malloc(size)
function : Dynamic storage in memory ( Heap area ) Allocate a piece with a length of size The contiguous area of bytes is used to store the type specified by the type specifier
The function prototype returns void The pointer , When using, you must do the corresponding forced type conversion
The content of the allocated memory space is uncertain , In general use memset initialization //memset(p,0,nsizeof(int))
Return value : The starting address of the allocated space ( Distribution succeeded )
null( Allocation failed )
Be careful :
1. Calling malloc after , Be sure to judge , Whether the memory request is successful
2. If you do it many times malloc Requested memory , The memory requested for the first and second time is not necessarily continuous
for example void *p(unsigned int 5);
2.ferr function ( Free memory function )
The header file :#include《stdlib,h》
Function definition :void free (void *ptr)
Function description :free Function to release ptr Memory pointed to
Be careful ptr The memory pointed to must be malloc calloc relloc Dynamically requested memory
// Free heap space Recycling of space usage rights Whether to clear the space content Not sure
3.calloc function // Automatic reset Unwanted memset
#include 《stdlib.h》
void *calloc(size_t nmemb,size_t size)
function : In the heap of memory , apply nmemb block , The size of each piece is size A contiguous area of bytes . Total size = nmemb * size
Parameters :size_t It's actually an unsigned integer , It is in the header file ,typedef Defined .
Return value :
return The first address of the requested memory ( Successful application )
return NULL( Application failed )
for example :char *p=(char=)calloc(3,100);
4.realloc Dynamically append or reduce space
#include《stdlib.h》
void* realloc(void *s,unsigned int newsize)
function : In the beginning s Re apply for memory based on the memory pointed to , The new memory size is new_size Bytes ,
If there is enough space behind the original memory , Just add ,
If there's not enough memory in the back , be relloc The function will find a in the heap newsize’ Memory request of bytes , Copy the contents of the original memory , Then release the original memory Finally, return the address of the new memory
Parameters : s The first address of the original memory
newsize: The size of the newly applied space
Return value : The first address of the newly requested memory
5. Precautions for the use of stack space
1. Pointer variable to heap space Don't arbitrarily change the direction
2. Do not operate the space that has been released
3. Do not release the space in the heap repeatedly // Solution if(p!=NULL){free(p);p=NULL;}
PS: Remember not to use free Prevent memory leaks .
String handling functions
As long as it is with str Initial function All encounter ’\0’ end
#include <string.h>
1.strlen Measure string length
Prototype :int strlen (const char *str)
function : Calculate string length , Not included ’\0’
Parameters : Memory space for storing strings The first address
explain : Formal parameters str use const modification , Express str The data in the space pointed to is read-only and cannot be modified
*size_t strlen (const char s)
s: The address of the first element of the measured string
Return value :str The length of It doesn't contain ’\0’
Not through s modify s Point to the content of the space
2. String copy function ( important )
strcpy
Prototype :char *strcpy(char *dest,const char *src)
function : hold src The string pointed to is assigned to desr In the space it points to
Return value : return dest The first address of the string
Be careful :’\0’ It'll be copied
strncpy
Prototype :char *strncpy(char *dest,const char *src ,int num)
function : hold src Point to the front of the string num Copy to dest In the space it points to
Return value : return dest The first address of the string
Be careful :’\0’ No copy
3. String splicing
stract
Prototype :char *strcat(char *dest,const char *src)
function : take src String spliced into dst At the end of (dst first ’\0’ The location of )
strncat
Prototype :char *strncat(char *str1,char *str2,int num)
function : take str2 front num Free trade links to str1 Back
Return value : return str1 The first address of the string
Be careful :‘\0’ Will copy it together
4. String comparison function ( important )
strcmp The whole string is compared
Prototype :int strcmp (char *str1,char *str2)
function : Compare str1 and str2 Size ; Compare one by one . Only equality compares the next
Return value : Equal return 0;
str1 Greater than str2 return 》0
str1 Less than str2 return 《0
str1=str2 return =0
strncmp String local comparison
String transformation function
strchr Character matching function
Prototype :char* strchr(const char *str1,char ch)
function : stay str1 In looking for ch Location of occurrence
Return value : Back to the first position
If not found, return null
strstr String matching function
Prototype :char *strstr (const char *s1,const char *s2)
function : from s1 In looking for s2
Return value : Find the location to return to for the first time
Cannot find return null
String handling functions
memset
Prototype :void* memset(void *str,char c ,int n)
function : take str Before the memory area pointed to n Use all c fill
Usually clear the specified space , Such as arrays or malloc Space
Return value : return str The address of
atoi/stol/atof Convert a string to a number
int atoi(const char *str)
long atol (const char *str)
double atof (const char *str)
function : take str The numeric string pointed to is converted to int\long\double
strtok String cutting function // The original string will be changed , Call cut once
*char *strtok(char s[],const char delim)
function : Literally
s Points to the string to be split
delim Is all the characters contained in the split string
When strtok() In the parameter s Parameter found in string of delim When you split characters contained in , The character will be changed to \0 character , When there are multiple in succession, only Ithaca The first is \0
( Ensure the success of the last cutting , Adopt the necessary for the next )
On the first call :strtok() Parameters must be given s character string . Later calls will take the parameter s Set to null, Yes, if the call is successful, it will return a pointer to the segmented fragment
Return value : Cutting success Returns the address of the first element cut to the character conversion segment Failure to return null
sprintf Package
printf Output to terminal
sprintf Output to Array of strings
fprintf Output to file
int sprintf(buf,“ Format ”, data )
buf: Used to store grouped messages
“ Format ”: Package according to format
data : Separate the scattered data with commas , Match one by one in order
Return value : The return value is the actual length of the grouped message ( It doesn't contain “\0”)
sscanf Unpack
sscanf(buf,“%dA%dB%dC”,&A,&B,&C);
%d Only map area 0-9
%c Only one character can be extracted
%f Only floating point numbers can be extracted
%s Extract a string Space encountered 、 enter 、‘\0’ Stop getting when
”%*s“ Flow pointer Take only Don't
Advanced usage
1. Use %*s %*d Skip extracting content
2. Use %[n]s %[n]d Extract a string or number of a specified width
Structure
Definition of structure
1. Structure type name :
Specify a structure type , It's equivalent to a model , But there is no specific data , The system doesn't allocate real memory units to it either
2. Structure variable name
The actual allocation of space one in order to be able to use structure type data in the program , Variables of structure type should be defined , And store specific data in it
1. Define the type first In defining variables ( recommend )
struct stu //struct Is the structure keyword stu Is the structure type name
{ // Use structure type Must be struct stu
int num; //num name age It's called a member of a structure
char name【32】;// When defining structure types Do not assign values to members ( important )
int age;
};
struct stu lucy;// Does not define lucy when No space
2. Define variables while defining types
struct stu
{
int num;
char name【32】;
int age;
}lucy;
Define a disposable structure
struct
{
int num;
char name【32】;
int age;
}lucy;
Measure the type of structure sizeof(struct stu); Type does not take up space Call to open
Output call lucy.num Access members in the structure ( Be sure to follow the member's own type ) num ==》int
printf(“num=%d\n”,lucy.num);
printf(“name=%s\n”,lucy.name);
matters needing attention :
1. Member references of structure variables must be used separately :
Structure variable name . Member name
2. It is allowed that structural variables with the same type can be assigned to each other
It is mostly used for the overall operation of structural members ( Sort, etc )
3. The structure can be initialized when it is defined
4. Allow nested definition of structural variables , Member reference multilevel reference
Structure variables get keyboard input
Statement :// A little
scanf(”%d %s %d“,&lucy.num,&lucy.name,&lucy.age);
Structure variable assignment
Mode one : Assign values to members one by one bob2.num=bob1.num; strcpy(bob2.name,bob1.name);
Mode two : Structural variables of the same type can be copied directly bob2=bob1;
Method 3 : The bottom implementation of method 2
memcpy(&bob,&lucy,sizeof(struct stu));
Array of structs // Each element of the array is a structure
struct stu arr[5];
take arr[2].name
struct stu arr[5]={ {100,‘100’,100},{100,‘100’,100},{100,‘100’,100}}
Bubble sort
arr 3 2 1 5 4
The first 0 round :j=0;j+1<n;j++// Inner circulation
The first 1 round :j=0;j+1<n-1;j++// Inner circulation
The first 2 round :j=0;j+1<n-2;j++// Inner circulation
The first 3 round :j=0;j+1<n-3;j++// Inner circulation
……
The first i round :j=0;j<n-i-1;j++// Inner circulation
use i It means the number of rounds :i=0;i<n-1;i++// The outer loop
if(arr[j]>arrr[j+1])
{
int tmp=0;
tmp =arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
}
for(i=0;i<n-1;i++){
int flag =0;
for(j=0;j<n-i-1;j++){
if(arr[j]>arrr[j+1]){
int tmp=0;
tmp =arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
flag=1;
}}
if(flag=0){ // It's in order
break;
}
}
Structure array sort
for(i=0;i<n-1;i++){
int flag =0;
for(j=0;j<n-i-1;j++){
if(arr[j].num>arrr[j+1].num){
struct stu tmp;// according to num The size order of
tmp =arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
flag=1;
}}
if(flag=0){ // It's in order
break;
}}
typedef Use steps // Alias an existing type
1. First define an entity with an existing type
2. Replace variable names with aliases
3. Before the whole expression add to typedef
Be careful : Can't create new types
Case study : Alias function pointers
int my_ add(int x,int y)
{
return x+y;
}
//FUN P Is a type of Li number pointer This function must have two int Formal parameters and a int Return value
typedef int (*FUN_ P)(int x,int y);
void test04( )
{
FUN_ P p = my_ _add;
printf("%d\n",p(100, 200));/ /300
}
Structure pointer That is, the address of the structure
&lucy : The first address of the structure
STU *p=&lucy;
*p==lucy;
Invocation format :
1.(*p).name (*p).age
2.p->name p->age
If . or -> On the left are ordinary structural variables Just use .
If . or -> On the left is the address use ->
3.lucy.name
Structure pointer variables cannot directly manipulate members , You must save an address .
#include <stdio.h>
#include <stdlib.h>
struct stu{
int id;
char name[32];
char sex;
int age;
};
void main(int argc,char *argv){
struct stu *s;// Define a structure pointer variable
// Open up the structure space in the heap and save its address in the structure pointer variable
s = (struct stu *)malloc(sizeof(struct stu));
s->id=1001;
strcpy(s->name," Zhang San ");
s->sex='Boy';
s->age=20;
printf("%d - %s - %c - %d \n",s-id,s->name,s->sex,s->age);
}
Structure memory allocation
The structure variable size is the sum of all members ?
But when actually allocating memory to the structure , There are rules .
The rules 1: How many bytes to open up memory
When allocating memory to structure variables , Will go to the structure variable to find the member of the basic type
Which basic type has more members in bytes , Take its large size as the unit to open up memory ,
stay gcc In the double Exceptions to type
(1): Of the members, only char Type data , With 1 Open up memory in bytes .
(2): There is... Among the members short Type data , There is no basic type data with a larger number of bytes .
With 2 Open up memory in bytes
(3): There is int float When there is no larger byte of basic type data, use 4 Open up memory in bytes .
(4): There is double Data of type
situation 1:
stay vc in , With 8 Open up memory in bytes .
situation 2:
stay gcc in , With 4 Open up memory in bytes .
Whatever the environment ,double Type variable , Occupy 8 byte .
Be careful :
If an array appears in the structure , An array can be seen as a collection of multiple variables .
If the pointer appears , There is no type that takes up a larger number of bytes , With 4 Open up memory in bytes .
When storing structure members in memory , Store in the order of defined structure members .
for example :
struct stu{
char sex;
int age;
}lucy; lucy Its size is 4 Multiple
The rules 2: Byte alignment
(1): char1 Byte alignment , Storage char Type variables , The number of the memory unit is 1 Multiple of .
(2): short int2 Byte alignment , Storage short int Type variables , The number of the starting memory unit is 2 Multiple of .
(3): int4 Byte alignment , Storage int Type variables , The number of the starting memory unit is 4 Multiple of
(4): longint stay 32 Under the platform ,4 Byte alignment , Storage long int Type variables , The number of the starting memory unit is 4 Multiple of
(5): float 4 Byte alignment , Storage float Type variables , The number of the starting memory unit is 4 Multiple of
(6) : double
a.vc In the environment 8 Byte alignment , Storage double Start address of type variable , Must be 8 Multiple , double Variables of 8 byte
b.gcc In the environment 4 Byte alignment , Storage double Start address of type variable , Must be 4 Multiple , double Variables of 8 byte .
Be careful 3: When an array appears in a structure member , It can be regarded as multiple variables .
Be careful 4: When opening up memory , Open up space from top to bottom according to the position of members in the structure
Specify the alignment principle :
Use #pragma pack Change the default to its principle
Format :#pragma pack (value) The specified alignment value for value.
Be careful :
1.value Can only be : 124 8 etc.
2. The specified alignment value is smaller than the data type alignment value
Structure pointer as parameter of function
Structure memory alignment :
Alignment rules :
1. Determine the allocation unit : The number of bytes that should be allocated to each row , The length of the largest basic type of structure is determined
2. Determine the offset of the starting position of the member = An integer multiple of the basic type of a member
3. Finishing work : Total size of structure == An integral multiple of the allocation unit
Structure nested structure : Structure 2 Make a structure 1 Members of
visit :data1.data2.name( Continue the type defined above )
//struct data1={10,20,30,40}
struct data1={10,20,{30,40}}// recommend
Structure nested structure memory alignment
1. Determine the allocation unit : The number of bytes that should be allocated to each row
The length of the largest basic type in all structures determines
2. Determine the cheap quantity of members = An integer multiple of its own type
If it is a structural member , Offset = The integer multiple of the largest basic type in the nested structure
Member offset in structure member Relative to the nested structure
3. Finishing work : The medium size of the structure = = An integral multiple of the allocation unit
Total size of structure members = = The maximum borrowing type integer multiple in the nested structure
Force type alignment
Specify alignment rules
1. Use #pragma pack Change the default alignment rules
Format :
#pragma pack(value) The specified alignment value for value
Be careful :
1.value Can only be :1 2 4 8 etc.
2. The specified alignment value is smaller than the data type alignment value
step :
1. Determine the allocation unit : The number of bytes that should be allocated to each row ,min(value, Default allocation unit )
2. Member offset = An integer multiple of the member's own type
3. Finishing work = An integral multiple of the allocation unit
// The order of the members of the structure can also affect the size of the structure
Use of bit segments
1. The access length of information in the computer is generally in bytes
2. Sometimes it is not necessary to use one or more bytes to store a piece of information
C Language allows a structure to specify the length of memory occupied by its members in bits , Members in bits are called “ Bit segment ” Or called “ Bit field ”
struct packed_ data {
unsigned int a:2;
unsigned int b:6;
unsigned int c:4;
unsigned int d:4;
unsigned int i;
} data;
among a, b, c, d Accounting for 2 position ,6 position ,4 position ,4 position ,;i Is an integer , Occupy 4 Bytes
Generally, only bit segments are considered unsigned int type You can also consider unsigned char
Adjacent bit fields can be compressed ( Compressed bits No more than The size of the member itself )
Use of bit segments :
Bit segment Address not available ( Not enough bytes , Address is in bytes )
Assignment of bit segments Do not exceed the size of the bit segment
char a:2
char :2// Meaningless bit segment ( Have two ) placeholder hold a b separate
char b:2
Bit segment attention :
1、 References to bit segment members are as follows : data.a =2 assignment , Do not exceed the range defined by the bit segment ; Such as paragraph members a set , Meaning is 2 position , The maximum value is 3, namely (11) 2 therefore data.a=5, Will take 5 Assign values to the lower two bits of 101
2、 The type of a bit segment member must be specified as integer or character
3、 A bit segment must be stored in one storage unit , Cannot span two cells. The first cell space cannot accommodate the next bit segment , Then the space is not used , The bit segment is stored from the next cell
The storage unit of the bit segment :
(1): char The type bit segment storage unit is 1 Bytes
(2): short int The bit segment storage unit of type is 2 Bytes
(3): int Bit segment of , The storage unit is 4 byte
(4): long int Bit segment of , The storage unit is 4 byte
The length of the bit segment cannot be greater than the length of the storage unit
(1): char Type bit segment cannot be greater than 8 position
(2): short int Type bit segment cannot be greater than 16 position
(3): int Bit segment of , Bit field cannot be greater than 32 position
(4): long int Bit segment of , Bit field cannot be greater than 32 position
You can define unintentional sememes , Such as :
unsigneda: 1;
unsigned : 2;
unsigned b: 3;
Shared body
1. When performing some algorithms , Several different types of variables need to be stored in the same memory unit , The memory space used by several variables overlaps with each other
2. This structure in which several different variables occupy a section of memory together is C In language , It's called “ Shared body ” Type structure
3. All members of the community occupy the same address space
The difference between structure and common body
Structure :struct All members have independent space
struct stu{
char a;
short b;
int c;
};//a b c Members have independent space
Shared body ( Consortium ):union
All the members Share the same space
union stu{
char a;
short b;
int c;
};// a b c Members share the same space
Space size of the community Decided by the largest member
The characteristics of Commons :
1、 The same memory segment can be used to store several different types of members , But there's only one thing that works in every instant
2、 The active member in the community variable is the last member stored , After saving a new member, the value of the original member will be overwritten
3、 The address of a common variable is the same as that of its members
4、 Initialization of common body variables union data a={123}; Initialize the community as - A member
Shared body : Take the value of the last assignment , The variable name points to the same
Although the community shares the same space , But the number of bytes read from space It is determined by the member's own type
enumeration
List the values of variables one by one , The value of a variable is limited to the values listed
Enumeration type definition
enmu Enum name
{
Enumeration table // Symbolic constant :hongtao,heitao=30,meihua=40,fangkuai
};
How to define enumeration variables
emnu Enumeration type name Enumerate variable names ;
All available values should be listed in the enumeration value table , Also known as enumeration elements
In the enumeration variable, only the elements listed in the enumeration value can be taken
// enmu Enum name HONGTAO = hongtao;
Enumerate the values of the list , The default from the 0 Start No assignment Increment by default
1. Enumeration values are constants , You can't assign a value to it with an assignment statement in a program
2. The enumeration element itself defines a numerical value representing the sequence number by the system Default 0,1,2,3,4 etc.
3. You can change the default value of the enumeration value
enmu week{
mon,tue=2,wed,thu=8,fri,set,sun
};
enmu week day = mon;
printf(“%d”,day);//0
enmu week day =tue;
printf("%d",day);//2
enmu week day = fri;
printf("%d",day);//9
Linked list
Array : Easy to traverse
Static array : Unable to make rational use of space
The dynamic array : It is not convenient to insert or delete data ( It will involve a lot of data movement )
Basic concepts : Linked list is a kind of discontinuous physical storage , The logical order of data elements is linked by pointers in the linked list , A linear storage structure
A linked list consists of a series of nodes , Nodes are running , Dynamic generation (malloc), Each node consists of two parts
1. Data fields where data is stored
2. Store the pointer field of the next node space
The composition of the list , Generally, the form of structural body type
Code implementation
Definition of linked list node :
typedef struct stu{
// Data fields ( Customize )
int num;
char name【32】;
float score;
// Pointer to the domain ( Save the next node address struct stu*)
struct stu *next;// Save the next node address
}STU;
Static list // Is not important Linked lists are dynamic
void test(){
STU *head =NULL;
STU *PB=head;// It cannot be defined below
STU data1={ };
STU data2={ };
STU data3={ };
STU data4={ };
STU data5={****};
head = &data1;
data1.next = &data2;
data2.next = &data3;
data3.next = &data4;
data4.next = &data5;
data5.next = NULL;
// Traversing the linked list
while(pb != NULL)
{
printf("%d %s %f \n",pb->num,pb->name,pb->score);
pb=pb->next;//pb Point to next node
}}
Dynamic linked list operation // The method of dividing files and functions
1. Layout the whole program framework
main.c
The header file : Definition , The declarations are in the header file
Prevent header files from repeatedly containing #pragma once
#ifndef LINK_H //linux With the more
#define LINK_H
// Linked list node type definition
typedef struct student{
// Data fields
int num;// Student number
int score;// fraction
char name[20];// full name
// Pointer to the domain
struct student *next
}STU;
#endif
// Creation of linked list
#include <stdio.h>
#include <stdlib.h>
// Linked list node type definition
typedef struct student{
// Data fields
int num;// Student number
int score;// fraction
char name[20];// full name
// Pointer to the domain
struct student *next
}STU;
void link_creat_head(STU **p_head,STU *p_new){
STU *p_mov = *p_head;
if(*p_head == NULL)// When the linked list is empty for the first time ,head perform p_new
{
*p_head = p_new;
p_new->next=NULL;
}else// Add the linked list after the second time
{
while(p_mov->next != NULL){
p_mov = p_mov -> next;// Find the last node of the original linked list
};
p_mov->next=p_new;// Add the newly applied node to the linked list
p_new->next=NULL;
};
};
int main(){
STU *head = NULL,*p_new=NULL;
int num,i;
printf(" Please enter the initial number of linked list :\n");
scanf("%d",&num);
for(i=0;i<num;i++){
p_new = (STU*)malloc(sizeof(STU));// Apply for a new node
printf(" Please enter the student number 、 fraction 、 name :\n");// Assign a value to the new node
scanf("%d %d %s",&p_new->num,&p_new->score,&p_new->name);
link_creat_head(&head,p_new);// Add the new node to the link
};
};
2. List traversal
void link_print(STU *head){
STU *p_mov;// Define a new pointer to save the first address of the linked list , Prevent the use of head Change the original linked list
p_mov = head;
// When the pointer saves the last node as NULL when , The loop ends
while(p_mov=head){
// First print the pointer field of the current pointer saving node
printf("num=%d score=%d name:%s\n",p_mov->num,p_mov->score,p_mov->name);
// Pointer backward , Save the address of the next node
p_mov = p_mov->next;
};
};
3. Linked list insertion node
1) Insert before the head
2) Tail insertion
3) The linked list is inserted orderly // Take a certain parameter as a reference
void link. _insert_ num(STU **p_ .head,STU *p_ _new)
{
STU *pb,*pf;
pb=pf=*p_ .head;
if(*p_ _head ==NULL)// The linked list is empty
{
*p_ _head = p_ .new;
p_ new->next=NULL;
return;
}
while((p_ new->num >= pb->num) && (pb->next !=NULL) )
{
pf=pb;
pb=pb->next;
if(p_ new->num < pb->num) // Find a node num Than the new node num Big , Plug in pb Back
{
if(pb== *p_ head)// The node found is the head node , Put it in the front
{
p_new->next=*p_head;
*p_head=p_new;
}
else
{
pf->next=p_ new;
p_ new->next = pb;
}
}
else// Can't find pb Of num Than p_ _new->num Big nodes , Insert at the end
{
pb->next =p_ new;
p_ new->next =NULL;
}
}
4. The search of linked list nodes Traverse the matching search
STU * link_search_num(STU *head,int num){
STU *p_mov;
// The defined pointer variable saves the address of the first node
p_mov=head;
// When the pointer field of the last node is not reached , The cycle continues
while(p_mov != NULL){
if(p_mov->num==num)// eureka
{
return p_mov;
}
p_mov=p_mov->next;
};
return NULL;// Can't find
}
5. Delete the linked list node
// Deletion of linked list nodes
void link_ delete_ num(STU **p_head,int num)
{
STU *pb, *pf;
pb=pf=*p_ head;
if(*p_ head == NULL)// Linked list is empty. , Don't delete
{
printf(" Linked list is empty. , There is no node you want to delete ");\
return ;
}
while(pb->num != num && pb->next !=NULL)// Circular search , The node to be deleted
{
pf=pb;
pb=pb->next;
}
if(pb->num == num) // eureka - One node num and num identical
{
if(pb == *p_head)// The node to be deleted is the head node
{
// Let the pointer to save the header node save the address of the next node
*p_head = pb->next;
}
else{
// The pointer field of the previous node saves the address of the next node to be deleted
pf->next = pb->next;
}
free(pb) ;
pb=NULL;
}
else// Did not find
{
printf(" There are no nodes you want to delete \n");
}
6. Release the linked list node — Must be released node by node
void link_free(STU **p_head){
// Define a pointer variable to store the address of the header node
STU *pb=*p_head;
while(*p_head!=NULL){
// First save p_head The address of the node pointed to
pb=*p_head;
//p_head Save the address of the next node
*P_head=(*p_head)->next;
// Release nodes and prevent wild pointers
free(pb);
pb=NULL;
};
};
7. Reverse order of linked list
8. Sorting of linked lists
Sorting by selection
Prerequisite : Pointer variable as a member of the structure
Shallow copy of structure : Pointer members in two struct variables point to the same space
Deep copy of structure : The pointer members in the two structure variables point to independent space
file
The basic concept of documentation
Disk files , Device file ( After drive optimization, it is similar to pointer )
1. File access process
Memory –> File buffer –> disk
Purpose of file buffer : Improve access efficiency And disk life
2. Disk file classification
Physically All disk files are binary Physically, it is sequential storage
logically ( User perspective ): text file Based on character encoding
Binary File based on value encoding
difference : 1. decoding
2. Space utilization
3. Readability
Opening and closing of files
C Language cannot directly manipulate files , Only library functions can be used to operate on files indirectly
When you open a file, you will get a file pointer fp
FILE * Pointer variable identifier // FILE *fp=NULL
FILE *fp = NULL;
fp =fopen( file name , How files are used );
fclose( The file pointer ) Close file
How files are used : The first parameter r w a + / The second parameter b t
r read-only
w Just write
a Additional
+ At the same time, it is opened by reading and writing
b Binary system
t Text
Byte read / write function :fgetc and fputc
ch=fgetc(fp);// Read a byte At the end of Text EFO;feof Binary
fputc(buf【i】,fp); Write... One by one
String read / write function : fgets and fputs
fgets(str,n,fp); Encounter line breaks or EOF End of extraction and read line breaks Add one at the end \0
Failure to return NULL The first element address is returned successfully
Data block read / write functions : fread and fwrite
fwrite Inconvenient to view But it does not affect program reading
Format read and write functions : fscanf and fprintf
Random reading and writing of files
No function Close and then open Give the first position to the pointer
rewind Reset the file stream pointer
ftell Get the current read / write location of the file stream Number of bytes returned
fseek function Move the read / write location of the file stream ( Mostly used for binary files )
fseek(fp,20,0/1/2) start / At present / At the end of
End of file detection function ( Binary is also available , Avoid binary unusable EOF Embarrassment )
feof( The file pointer ) The return value does not end. Return 0 The end is not 0
Error detection function for reading and writing files
ferror( The file pointer ); Return value 0 No mistakes Otherwise there is a mistake
File error flag and file end standard setting 0 function
ckearerr( The file pointer );
File encryption
Symmetric encryption : The same key Encryption and decryption
File Encryptor
1. Principle analysis
The encryption process :
The decryption process :
Detailed design api Reference resources // Others give you api, But it is not perfect
// No standard library is declared
#include"fun.h"
int main(){
while(1){
int cmd=0;
print_help();
scanf("%d",&cmd);
if(cmd=1){
char src_file[31]="";
char dest_file[31]="";
unsigned long file_length=0;
char *file_data=NULL;
char *data=NULL
unsigned int passward = 0;
//1. Get the destination file name of the source file
//void get_file_name(char *dest_file_name,char *src_file_name)
get_file_name(dest_file[31],src_file[31]);
//2. Get the source file name Corresponding file Content
//char * read_src_file(unsigned long *file_length,char *src_file_name)
file_data = read_src_file(&file_length,src_file[31]);
//3. Get user input password
printf(" Please input a password ");
scanf("%u",&passward);
//4. Encrypt the contents of the file
//char *file_text_encrypt(char *src_file_text,unsigned long int length,unsigned int passward)
file_data=file_text_encrypt(file_data,file_length,passward );
//5. Encrypted file content Save to the destination file name
//void save_file(char* text,unsigned long int length,char *file_name)
save_file(file_data,file_length,dest_file);
}else if(cmd=2){
//1. Get the destination file name of the source file
//void get_file_name(char *dest_file_name,char *src_file_name)
get_file_name(dest_file[31],src_file[31]);
//2. Get the source file name Corresponding file Content
//char * read_src_file(unsigned long int *file_length,char *src_file_name)
file_data = read_src_file(&file_length,src_file[31]);
//3. Get user input password
printf(" Please input a password ");
scanf("%u",&passward);
//4. Decrypt file contents
//char *file_text_decrypt(char *src_file_text,unsigned long int length,unsigned int passward)
file_text_decrypt(file_data,file_length,passward);
//5. Encrypted file content Save to the destination file name
//void save_file(char* text,unsigned long int length,char *file_name)
save_file(file_data,file_length,dest_file);
}else if(cmd=3){
}else{
printf(" Please enter legal options ")
}
};
return 0;
}
//fun.h The code base
void print_help(void){
printf("*****1. Encrypt file ******\n")
printf("*****2. Decrypt files ******\n")
printf("*****3. Exit procedure ******\n")
}
void get_file_name(char *dest_file_name,char *src_file_name){
printf("please input your yuanwenjian 30char")
scanf("%s",src_file_name);
printf("please input your mudiwenjian 30char")
scanf("%s",dest_file_name);
return;
}
char * read_src_file(unsigned long *file_length,char *src_file_name){
FILE *fp =NULL;
fp=fopen(src_file_name,"r");
if(fp==NULL){
perror("fopen");
return NULL;
}
// Get file length
fseek(fp,0,2);
*file_length=ftell(fp);
rewind(fp);
// Apply for heap space according to the length of the document
data=(char * )calloc(1,*file_length);
if(data==NULL){
perror("calloc");
return NULL;
}
// Read the contents of the file at one time
fread(data,(1,*file_length,1,fp);
// Return space
return data;
}
char *file_text_encrypt(char *src_file_text,unsigned long int length,unsigned int passward){
int i=0;
for(i=0;i<length;i++){
src_file_text[i] += passward;
}
return src_file_text;
}
void save_file(char* text,unsigned long int length,char *file_name){
FILE *FP =NULL;
fp = fopen(file_name,"w");
if(fp==NULL){
perror("fopen");
return;
}
fwrite(text,length,1,fp);
fclose(fp);
if(text!=NULL){
free(text);
text=NULL;
}
printf(" Saved successfully !\n");
}
char *file_text_decrypt(char *src_file_text,unsigned long int length,unsigned int passward){
int i=0;
for(i=0;i<length;i++){
src_file_text[i] -= passward;
}
return src_file_text;
}
//fun.c Statement c file
#ifndef __FUN_H__
#define __FUN_H__
extern void print_help(void);
extern void get_file_name(char *dest_file_name,char *src_file_name);
extern char * read_src_file(unsigned long *file_length,char *src_file_name);
extern char *file_text_encrypt(char *src_file_text,unsigned long int length,unsigned int passward)
extern void save_file(char* text,unsigned long int length,char *file_name)
extern char *file_text_decrypt(char *src_file_text,unsigned long int length,unsigned int passward)
#endif
To be continued , Daily update
Follow up updates on the in-depth study of pointers and structures
边栏推荐
- Common system modules and file operations
- Ten key performance indicators of software applications
- 2022 AAAI fellow release! Yan Shuicheng, chief scientist of sail, and Feng Yan, Professor of Hong Kong University of science and technology, were selected
- [Galaxy Kirin V10] [desktop] FTP common scene setup
- Canoe - the third simulation project - bus simulation - 3-2 project implementation
- Performance test overview
- Software sharing: the best PDF document conversion tool and PDF Suite Enterprise version sharing | with sharing
- Aike AI frontier promotion (2.14)
- Oracle11g | getting started with database. It's enough to read this 10000 word analysis
- Unittest+airtest+beatiulreport combine the three to make a beautiful test report
猜你喜欢
[test theory] test process management
JMeter common configuration components and parameterization
Canoe test: two ways to create CAPL test module
C language structure to realize simple address book
[Galaxy Kirin V10] [desktop] FTP common scene setup
Using Lua to realize 99 multiplication table
Hidden C2 tunnel -- use of icmpsh of ICMP
JMeter Foundation
DDL statement of MySQL Foundation
Open the neural network "black box"! Unveil the mystery of machine learning system with natural language
随机推荐
Summary of several job scheduling problems
DNS hijacking
[Galaxy Kirin V10] [server] iSCSI deployment
Day7 list and dictionary jobs
Network connection (II) three handshakes, four waves, socket essence, packaging of network packets, TCP header, IP header, ACK confirmation, sliding window, results of network packets, working mode of
2022 ape circle recruitment project (software development)
Safety testing aspects
Huge number (C language)
JMeter assembly point technology and logic controller
Fundamentals of software testing
I What is security testing
[Galaxy Kirin V10] [server] FTP introduction and common scenario construction
[Galaxy Kirin V10] [server] soft RAID configuration
Snake (C language)
Strings and characters
Write a program to define an array with 10 int elements, and take its position in the array as the initial value of each element.
Unittest+airtest+beatiulreport combine the three to make a beautiful test report
Deepmind proposed a Zuan AI, which specially outputs network attack language
JMeter common configuration components and parameterization
/*The rewriter outputs the contents of the IA array. It is required that the type defined by typedef cannot be used in the outer loop*/