1, Weng Kai C language
1. There are two ways to define macro constants
const int AMOUNT=100; or #define AMOUNT 100
2. Floating point number
//float is a single precision floating point number //Double is a double precision floating-point number
3. Data type
//integer int printf("%d",...) scanf("%d",...) //Number with decimal point double printf("%f",...) scanf("%lf",...) //Floating point number input must use% lf
4. Compound assignment
total+=5; equal total=total+5; // total+=(sum+100)/2; equal total=total+(sum+100)/2; // total*=sum+12; equal total=total*(sum+12); // total/=12+6; equal total=total/(12+6);
++And –
//++And -- can be placed in front of the variable, called prefix form, or behind the variable, called suffix form. //The value of a + + is the value before a plus 1, while the value of + + A is the value after 1. No matter which, a's own value has been added 1. #include<stdio.h> int main() { int a=10; printf("a++=%d\n",a++); printf("a=%d\n",a); printf("++a=%d\n",++a); printf("a=%d\n",a); return 0; } //Output results /* a++=10 a=11 ++a=12 a=12 */
Expression: count + + operation: add 1 to count. Value of expression: original value of count
Expression: + count operation: add 1 to count. Value of expression: value after count+1
5. Result of relation operation
//When the relationship between two values conforms to the expiration date of the relational operator, the result of the relational operation is an integer 1, otherwise it is an integer 0 printf("%d\n",5==3); printf("%d\n",5>3); printf("%d\n",5<=3); //Output results 0 1 0
6. Priority of relation operation
All relational operators have lower priority than arithmetic operations, but higher priority than assignment operations
//7>=3+4; //int r=a>0; #include<stdio.h> int main(){ printf("%d\n",7>=3+4); int a=5; int r=a>0; printf("r=%d\n",r); return 0; //Output results 1 r=1
Determine whether equal = = and= The priority of is lower than others, and the continuous relational operation is carried out from left to right
/* 5>3==6>4 6>5>4 a==b==6 a==b>0 */ #include<stdio.h> int main() { printf("%d\n",5>3==6>4); printf("%d\n",6>5>4); int a,b=5; printf("%d\n",a==b==6); printf("%d\n",a==b>0); return 0; } //Output results 1 0 0 1
7.if statement
//When there are no braces after an if or else statement, only the following sentence is valid //Calculate salary #include<stdio.h> int main(){ const double RATE=8.25; const int STANDARD=40; double pay=0.0; int hours; printf("Please enter the number of working hours:"); scanf("%d",&hours); if(hours>STANDARD) pay=STANDARD*RATE+(hours-STANDARD)*(RATE*1.5); else pay=hours*RATE; printf("Wages payable:%f\n",pay); return 0; }
8.switch-case
switch(Control expression){ case constant: sentence ..... case constant: sentence ..... case constant: sentence ..... default: sentence ..... } //This control expression can only be an integer result //Constants can be constants or expressions for constant calculations /*case 1+1: or */ /*const int MRN=2; case MRN: */
The function of break is that if there is no break, it will be executed in the following case s in sequence until a break is encountered or the switch ends
#include <stdio.h> int main(){ int type; scanf("%d",&type); switch(type){ case 1: case 2: printf("hello"); break; case 3: printf("good morning\n"); case 4: printf("goodbye"); break; default: printf("what's up"); break; } return 0; } //Output results 1 hello 2 hello 3 good morning goodbye //NOTE:case is just an entrance, and break is the exit
9.while loop and do while loop
//Determine how many digits a positive number is #include<stdio.h> int main(){ int x; int n=0; scanf("%d",&x); n++; //x/=10 cross out the numbers at the end in turn x/=10; while(x>0){ n++; x/=10; } printf("%d\n",n); return 0; }
When entering the loop, do not check, but check whether the conditions of the loop are met after executing the code of one round of loop body. If they are met, continue the next round of loop, and if not, end the loop
do { <Loop body statement> }while(<Cycle condition>);
//If the code above is written in do while #include<stdio.h> int main(){ int x; int n=0; scanf("%d",&x); /*n++; //x/=10 Cross off the numbers at the end in turn x/=10; while(x>0){ n++; x/=10; }*/ do{ x/=10; n++; }while(x>0); //When you execute do while, the loop body will be executed at least once, even if the result does not meet the loop conditions printf("%d\n",n); return 0; }
10. Guessing game
NOTE:%100
The result of x%n is an integer of [0,n-1]
#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ //rand() generates a random number //rand()%100 can randomly generate a random number from 0 to 99 //rand()%100+1 can randomly generate a random number from 1 to 100 srand(time(0)); int count=0; int number=rand()%100+1; int a; do{ printf("Please enter a 0-100 Number of"); scanf("%d",&a); count++; if(a>number){ printf("The number entered is too large"); }else if(a<number){ printf("The number entered is too small"); } }while(a!=number); printf("Great, you used it%d I guessed right",count); return 0; }
11. Average
#include<stdio.h> #include<math.h> #include<stdlib.h> int main(){ int count=0; int t=0; double average=0.0; int number=0; while(number!=-1){ scanf("%d",&number); if(number!=-1){ count++; t+=number; }else{ average=(1.0*t)/count; printf("average=%f",average); } } return 0; }
12. Integer reverse order
#include<stdio.h> int main(){ //123-321 int x; int digit; scanf("%d",&x); //123%10=3 //123/10=12 //12%10=2; //12/10=1 //1%10=1 while(x>0){ digit=x%10; printf("%d",digit); x/=10; } return 0; }
13. Number of for cycles
#include<stdio.h> int main(){ int i; for(i=0;i<5;i++){ printf("i=%d",i); } printf("\n last i=%d\n",i); return 0; //Equivalent to /* for(i=1;i<=5;i++){ printf("i=%d",i); } printf("\n Last i=%d\n",i); return 0; } */
14. Difference between break and continue
break directly jumps out of the loop. continue jumps out of this loop and executes the next loop
//break directly jumps out of the loop //continue is to jump out of this loop and execute the next loop #include<stdio.h> int main(){ int i; for(i=0;i<5;i++){ printf("%d",i); continue; printf("hello world"); } return 0; } //Output results 0 1 2 3 4
#include<stdio.h> int main(){ int i; for(i=0;i<5;i++){ printf("%d\n",i); break; printf("hello world"); } return 0; } //Output results 0
15. Output all prime numbers within 100
#include<stdio.h> int main(){ int x; for(x=1;x<100;x++){ int i; int isprime=1; for(i=2;i<x;i++){ if(x%i==0){ isprime=0; break; } } if(isprime==1){ printf("%d\n",x); } } return 0; }
16. Chip games
#include<stdio.h> int main(){ //How to use dimes, dimes and dimes to make up an amount of less than 10 yuan int x; int one,two,five; scanf("%d",&x); for(one=1;one<x*10;one++){ for(two=1;two<x*10/2;two++){ for(five=1;five<x*10/5;five++){ if(one+two*2+five*5==x*10){ printf("Can use%d A corner and%d Two corners and%d Five corners make up%d A dollar\n",one,two,five,x); } } } } return 0; } //Output results 2 You can use one dime, two dimes and three pentagons to make two one yuan You can use one dime, seven dimes and one Pentagon to make two one yuan You can use two dimes, four dimes and two pentagons to make two one yuan You can use three dimes, one dime and three pentagons to make two one yuan You can make 2 one yuan with 3 one jiao, 6 two jiao and 1 five jiao You can make 2 one yuan with 4 one jiao, 3 two jiao and 2 five jiao You can use five dimes, five dimes and one Pentagon to make two one yuan You can make 2 one yuan with 6 one jiao, 2 two jiao and 2 five jiao You can use seven dimes, four dimes and one Pentagon to make two one yuan You can make 2 one yuan with 8 one jiao, 1 two jiao and 2 five jiao You can use 9 dimes, 3 dimes and 1 Pentagon to make 2 one yuan You can use 11 dimes, 2 dimes and 1 Pentagon to make up 2 one yuan You can use 13 one jiao, 1 two jiao and 1 five jiao to make 2 one yuan //Just use break to output a situation #include<stdio.h> int main(){ //How to use dimes, dimes and dimes to make up an amount of less than 10 yuan int x; int one,two,five; scanf("%d",&x); int exit=0; for(one=1;one<x*10;one++){ for(two=1;two<x*10/2;two++){ for(five=1;five<x*10/5;five++){ if(one+two*2+five*5==x*10){ printf("Can use%d A corner and%d Two corners and%d Five corners make up%d A dollar\n",one,two,five,x); exit=1; break; } } if(exit)break; } if(exit)break; } return 0; } //Output results 2 You can use one dime, two dimes and three pentagons to make two one yuan
It's called relay break
You can also use the goto statement, as follows:
#include<stdio.h> int main(){ //How to use dimes, dimes and dimes to make up an amount of less than 10 yuan int x; int one,two,five; scanf("%d",&x); for(one=1;one<x*10;one++){ for(two=1;two<x*10/2;two++){ for(five=1;five<x*10/5;five++){ if(one+two*2+five*5==x*10){ printf("Can use%d A corner and%d Two corners and%d Five corners make up%d A dollar\n",one,two,five,x); goto out; } } } } out: return 0; } //Output results 2 You can use one dime, two dimes and three pentagons to make two one yuan
17. Find the sum of the first n items
//1+1/2+1/3+1/4+...+1/n #include<stdio.h> int main(){ int n; scanf("%d",&n); int i; double sum=0.0; for(i=1;i<=n;i++){ sum+=1.0/i; } printf("f(%d)=%f",n,sum); return 0; }
//1-1/2+1/3-1/4+1/5-...+1/n #include<stdio.h> int main(){ int n; scanf("%d",&n); int i; double sum=0.0; double sign=1.0; for(i=1;i<=n;i++){ sum+=sign/i; sign=-sign; } printf("f(%d)=%f\n",n,sum); return 0; }
18. Data type
//integer char,short,int,long,long long //Floating point number float,double,long double //logic bool //Pointer //Custom type //sizeof is an operator that gives the number of bytes occupied by a type or variable in memory sizeof(int)//int occupies a few bytes in memory sizeof(i)//i this variable occupies a few bytes in memory #include<stdio.h> int main(){ int a; a=6; printf("sizeof(int)=%lf\n",sizeof(int)); printf("sizeof(double)=%lf\n",sizeof(double)); printf("sizeof(a)=%lf\n",sizeof(a)); return 0; } //Output results sizeof(int)=4 sizeof(double)=8 sizeof(a)=4 #include<stdio.h> int main(){ printf("sizeof(char)=%ld\n",sizeof(char)); printf("sizeof(short)=%ld\n",sizeof(short)); printf("sizeof(int)=%ld\n",sizeof(int)); printf("sizeof(long)=%ld\n",sizeof(long)); printf("sizeof(long long)=%ld\n",sizeof(long long)); return 0; } //Output results sizeof(char)=1 sizeof(short)=2 sizeof(int)=4 sizeof(long)=8 sizeof(long long)=8
19.unsigned
//The original intention of unsigned is not to expand the range that can be expressed by numbers, but to do pure binary operations, mainly for shift #include<stdio.h> int main(){ char c=255; //255 binary is 11111111,2 to the 8th power - 1 //No unsigned means that the highest bit is the sign bit, so the output result is - 1 printf("%d",c); return 0; } //Output results -1 #include<stdio.h> int main(){ unsigned char c=255; printf("%d",c); return 0; } //Output results 255
20. Input and output of integers
There are only two forms of input and output of integers: int and long long %d:int %u:unsigned %ld:long long %lu:unsigned long long
21. Output accuracy
float has 7 valid digits and double has 15 valid digits
//Add. n between% and f to specify the number of decimal places after the output. Such output is rounded to 4 //%3.0f the first number is the character width, and the last number is the number of decimal places #include<stdio.h> int main(){ printf("%.3f\n",-0.0049); printf("%.30f\n",-0.0049); printf("%.3f\n",-0.00049); return 0; } //Output results -0.005 -0.004899999999999999800000000000 -0.000
22. Floating point number out of range
//printf output inf represents a floating-point number out of range //printf output nan represents a non-existent floating-point number #include<stdio.h> int main(){ printf("%f\n",12.0/0.0); printf("%f\n",-12.0/0.0); printf("%f\n",0.0/0.0); return 0; } //Output results inf -inf nan
Literal quantity with decimal point is double instead of float. Float needs to be suffixed with f or F
f1==f2 May fail So use fabs(f1-f2)<1e-12//The absolute value of f1-f2 is less than 1e-12
If there are no special requirements and just use double, modern cpu can directly perform hardware calculation on double, and the performance will not be worse than float. On 64 bit machines, the speed of data storage will not be slower than float
23. Character type
/* 1.char Is an integer and a special type: character. This is because: 2.Use single quotation marks to indicate character literal: 'a','1' 3.''Is also a character 4.printf Use% c to input and output characters in and scanf */ #include<stdio.h> int main(){ char c; char d; c=1; d='1'; if(c==d){ printf("equal\n"); }else { printf("c=%d\n",c); printf("d=%d\n",d); } return 0; } //Output results Unequal c=1 d=49 //How to input the character '1' to char c //There are two ways, as follows: //Method 1 #include<stdio.h> int main(){ char c; scanf("%c",&c); printf("c=%d\n",c); printf("c='%c'\n",c); return 0; } //Output results 1 c=49 c='1' //Method 2 #include<stdio.h> int main(){ char c; int d; //Because% d is in scanf, it can only be accepted with int, so an int shaped variable D is used scanf("%d",&i); d=i; printf("c=%d\n",c); printf("c='%c'\n",c); return 0; } //Output results 49 c=49 c='1'
%The space in the middle of d% C means until the space is not read later
#include<stdio.h> int main(){ char c; int i; scanf("%d %c",&i,&c); printf("i=%d c=%d c='%c'\n",i,c,c); return 0; } //Output results 12 1 i=12 c=49 c='1' #include<stdio.h> int main(){ char a; int b; scanf("%d%c",&a,&b); printf("a=%d b=%d b='%c'\n",a,b,b); return 0; } //Output results 12 1 a=12 b=32 b=' '
24. Escape character
/* \b Back one space \t To the next table bit \n Line feed \r enter \''Double quotation mark \'Single quotation mark \\Backslash itself */ #include<stdio.h> int main(){ printf("123\bA\n456\n"); return 0; } //Output results 12A 456
25. Automatic type conversion
For printf, any type less than int will be converted to int; float will be converted to double, so% f can output double without% lf, because% f is automatically converted to% lf in printf. But scanf won't. to enter short,% hd is required.
26. Cast type
To cast a quantity to another type (usually a smaller type), you need a: (type) value
//(int)10.2 //(short)32 Pay attention to the safety at this time. Small variables do not always express large quantities //(short)32768
//Casts take precedence over four operations double a=1.0; double b=2.0; int i=(int)a/b; //int i=(int)(a/b);
26.bool type
#include<stdbool.h> //Then you can use bool and true, false
27. Conditional operation and comma operation
m<n ? x : a+5//If M < n, the result is x, otherwise it is a+5 a++>=1 && b-->2 ? a:b//If both are satisfied, the result is a, otherwise it is b //Comma expressions are mainly used in for conditions, which is basically the only use for(i=10,j=5;i<=20;i++,j--)
28. Function value transfer
Each function has its own variable space, and the parameters are also located in this independent space, which has nothing to do with other functions
In the past, the parameters in the function parameter table were called "formal parameters", and the values given when calling the function were called "actual parameters". We do not recommend that we continue to call them in this ancient way
Now, we call them parameters and values. The only thing that happens in the middle is to pass values
29. Local variable (local variable)
30. Example of array: count the number
//Write a program, input an integer within the uncertain range of [0,9], count the number of occurrences of each number, and enter - 1 to end #include<stdio.h> int main(){ int i; int x; int count[10]; //Initialize array for(i=0;i<10;i++){ count[i]=0; } scanf("%d",&x); while(x!=-1){ if(x>=0 && x<=9){ count[x]++; } scanf("%d",&x); } for(i=0;i<10;i++){ printf("%d:%d\n",i,count[i]); } return 0; }
31. Array operation
Array initialization
#include<stdio.h> int main(){ int i; //Pay attention to this way of writing int number[10]={[1]=2,4,[5]=6}; for(i=0;i<10;i++){ printf("%d\t",number[i]); } return 0; } //Output results 0 2 4 0 0 6 0 0 0 0
The size of the array
sizeof(a)/sizeof(a[0]); //sizeof(a[0]) gives the size of a single element, so division is the number of cells in the array //Such code, once the initial data in the array is modified, there is no need to modify the traversal code
Assignment of array
Array variables themselves cannot be assigned To give all the elements of an array to another array, traversal must be used #include<stdio.h> int main(){ int a[]={1,2,3}; //int b[]=a;// This is wrong and can only be traversed for(i=0;i<length;i++){ b[i]=a[i]; } return 0; }
//Determine the subscript of the number in the array #include<stdio.h> int main(){ int a[]={1,2,3,4,6}; int x; int loc; printf("Please enter a number:"); scanf("%d",&x); loc=search(x,a,sizeof(a)/sizeof(a[0])); if(loc!=-1){ printf("%d In the first%d In two places\n",x,loc); }else{ printf("non-existent"); } return 0; } int search(int key,int a[],int length){ int i; int ret=-1; for(i=0;i<length;i++){ if(a[i]==key){ ret=i; break; } } return ret; } //Output results Please enter a number:2 2 In position 1
32. Two dimensional array
int a[3][5] is a matrix with three rows and five columns
//Traversal of two-dimensional array //such as for(i=0;i<3;i++){ for(j=0;j<5;j++){ a[i][j]=i*j; } } //2D array initialization int a[][5]={ {0,1,2,3,4}, {2,3,4,5,6}, } //The number of columns must be given, and the number of rows can be counted by the compiler //One {} for each line, separated by commas //The last comma can exist, there is an ancient tradition //If omitted, it means complement 0
33. Address calculation
1. Operator &, obtain the address of the variable, and its operand must be a variable.
2.int i;printf("%x",&i);
3. Whether the size of the address is the same as int depends on the compiler
4.int i;printf("%p",&i);
5. & you can't take an address for something without an address
34. Pointer
/* Pointer: the variable that holds the address int i; int* p=&i; //These two ways of writing indicate that p is a pointer and q is an int variable, but the writing methods are different int* p,q; int *p,q; //p And q are pointers int *p,*q; ********************************* Pointer as parameter void f(int *p); When called, you get the address of a variable: int i=0;f(&i); In the function, you can access the i outside through this pointer */ #include<stdio.h> void f(int *p); int main(){ int i=6; printf("&i=%p\n",&i); f(&i); return 0; } void f(int *p){ printf("p=%p\n",p); } //Output results &i=000000000062FE4C p=000000000062FE4C
/* Access variables at that address* 1.*Is a unary operator used to access variables at the address represented by the value of the pointer 2.It can be an R-value or an l-value //*It means to access the variable at the address pointed to by the pointer 3.int k=*p; 4.*p=k+1; 5.*p This whole can be regarded as a variable value */
Pointer operator
/* 1.Mutual reaction 2.*&yptr->*(&yptr)->*(yptr Get the variable at that address - > yptr 3.&*yptr->&(*yptr)->&(y)->Get the address of y, that is yptr - > yptr */
What does a pointer do
/* 1.Pointer application scenario 1: exchange the values of two variables void swap(int *pa,int *pb) { int t=*pa; *pa=*pb; *pb=t; } */ #include<stdio.h> int main(){ int a=5,b=3; swap(&a,&b); printf("a=%d,b=%d\n",a,b); return 0; } void swap(int *pa,int *pb){ int t=*pa; *pa=*pb; *pb=t; } //Output results a=3,b=5 /* 2.Pointer application scenario 2 Function returns multiple values, and some values can only be returned through pointers The parameters passed in are actually variables that need to save the results brought back */ #include<stdio.h> void minmax(int a[],int len,int *min,int *max); int main(){ int a[]={1,2,3,4,5,6,7,8,9,13,45,67}; int min,max; minmax(a,sizeof(a)/sizeof(a[0]),&min,&max); printf("min=%d,max=%d\n",min,max); return 0; } void minmax(int a[],int len,int *min,int *max){ int i; *min=*max=a[0]; for(i=1;i<len;i++){ if(a[i]<*min){ *min=a[i]; } if(a[i]>*max){ *max=a[i]; } } } //Output results min=1,max=67 /* Pointer application scenario II b 1.Function returns the state of the operation, and the result is returned through the pointer 2.A common routine is to let the function return a special value that does not belong to the valid range to indicate an error 3.-1 Or 0 (you will see a lot of examples in file operation) 4.However, when any value is a valid possible result, it has to be returned separately (the status is returned through retun and the result is returned through pointer) */ #include<stdio.h> int main(){ int a=5; int b=2; int c; if(divide(a,b,&c)){ printf("%d/%d=%d\n",a,b,c); } return 0; } int divide(int a,int b,int *result){ int ret=1; if(b==0)ret=0; else{ *result=a/b; } return ret; }
Pointer is the most common error
1. The pointer variable is defined, and the pointer is used before pointing to any variable
such as
int *p;
*p=12; It's wrong
35. Pointers and arrays
/* 1.The array in the function parameter table is actually a pointer 2.sizeof(a)==sizeof(int*) 3.However, you can operate with the operator [] of the array */
Array parameters /* The following four function prototypes are equivalent 1.int sum(int *ar,int n); 2.int sum(int *,int); 3.int sum(int a[],int n); 4.int sum(int [],int); Array variables are special pointers 1.Array variables themselves express addresses, so int a[10];int* p=a;//No & Address However, the cells of the array represent variables, and the address needs to be taken with & a==&a[0] 2.[]Operators can be applied to arrays or pointers: p[0]<==>a[0] If p is an array, * p represents the address of the first array element, so * p and p[0] are equivalent 3.*Operators can be used for pointers or arrays: *a=25; 4.Array variables are pointers to const, so they cannot be assigned //Array variables cannot be assigned to each other int a[]; int b[]; b=a//error */
36. Pointer and const
//Indicates that once the address of a variable is obtained, it can no longer point to other variables int *const q=&i;//q is const *q=26;//OK q++;//The fact that q is the address of i and q points to i cannot be changed //Const refers to const 1.Indicates that the variable cannot be modified through this pointer (it does not make the variable const) 2.const int* p=&i; 3.*p=26;//ERROR (* p) is const 4.i=26;//OK 5.p=&i;//OK NOTE:Pay attention to the difference between the two What do these mean int i; const int* p1=&i; int const* p2=&i; //The first two consts are in front of the * sign, so the meaning is the same, that is, the variable i cannot be modified through this pointer. It can be understood that * p1 is const, that is, the data i can't be modified int *const p3=&i; //const after the * sign indicates that the pointer cannot be modified, that is, it points to the address of i and can no longer point to the address of other variables Judge which is const The sign is const stay*Is it in front of or behind the number transformation You can always put a non const Convert the value of to const of void f(const int *x); int a=14; f(&a);//ok const int b=a; f(&b);//ok b=a+1;//ERROR This is a common method when the type of the parameter to be passed is larger than the address; that is, the value can be passed to the parameter with a relatively small number of bytes, and the modification of external variables by the function can be avoided const array 1.const int a[]={1,2,3,4}; 2.Array variable is already const The pointer here const Indicates that each cell of the array is const int 3.Therefore, the value must be assigned through initialization Protect array values 1.Because the address is passed when the array is passed into the function, the value of the array can be modified inside the function 2.To protect the array from being destroyed by the function, you can set the parameter to const 3.int sum(const int a[],int length); //In this case, the array a cannot be modified in the sum function
37. Pointer operation
/* 1.These arithmetic operations can be performed on pointers 2.Add or subtract an integer (+, + =, -, - =) to the pointer 3.Increasing decreasing (+ + / -) 4.Two pointers can be subtracted *p++ //Take out what p refers to, and by the way, put p+1 1.Take out the data referred to by P and move p to the next position when you're done 2.*Although the priority of is high, it is not as high as + + 3.It is often used for continuous space operations of array classes 4.On some CPU s, this can be translated directly into an assembly instruction */ #include<stdio.h> int main(){ int a[]={1,2,3,4,5,-1}; int *p; p=a; //Traversing arrays with * p + + while(*p!=-1){ printf("%d\t",*p++); } return 0; } //Output results 1 2 3 4 5 Pointer comparison 1.<,<=,==,>,>=,!=Can be done on the pointer 2.Compare their addresses in memory 3.The addresses of the cells in the array must be linearly increasing 0 address 1.Of course, you have 0 address in your memory, but 0 address is usually an address that you can't touch casually 2.So your pointer should not have a value of 0 3.Therefore, you can use the 0 address to represent special things The returned pointer is invalid The pointer was not really initialized (initialized to 0 first) 4.NULL Is a predefined symbol representing the 0 address 5.Some compilers don't want you to use 0 to represent 0 address Pointer type conversion 1.void* A pointer indicating that you don't know what to point to Calculation and char*Same (but not interlinked) 2.Pointers can also convert types int *p=&i;void* q=(void*)p; 3.This has not changed p It refers to the type of variable, but allows future generations to pass it with different eyes p Look at the variable it refers to I no longer think you are int Well, I think you are void! What do you do with a pointer 1.It is used as a parameter when large data needs to be passed in 2.Operate on the array after passing in the array 3.Function returns more than one result 4.You need a function to modify more than one variable 5.Dynamically requested memory...
38. Dynamic memory allocation
malloc
#include<stdlib.h>
void* malloc(size_t size);
1. The space size applied to malloc is in bytes
2. The returned result is void *, which needs to be converted to its own type
3.(int*)malloc(n*sizeof(int));
free(name);
//example #include<stdio.h> #include<stdlib.h> int main(){ int number; int *a; int i; printf("Enter quantity:\n"); scanf("%d",&number); a=(int*)malloc(number*sizeof(int)); for(i=0;i<number;i++){ scanf("%d",&a[i]); } for(i=number-1;i>=0;i--){ printf("%d",a[i]); } free(a); return 0; } //Output results Enter quantity: 3 1 2 3 321 free 1.Return the requested space to the system 2.The space applied for should be returned in the end 3.Only the first address of the space still applied for It is a good habit to write programs. If any pointer is defined, it will initially be 0 void* p=0; free(p);//This is no problem Common problems 1.Did you apply free->Running for a long time, the memory gradually decreases 2.Novice: I forgot 3.Veteran: I can't find the right one free Timing 4.free After a while free,Will collapse
39. String
//Character array char word[]={'H','E','L','L','O'}; word[0]=H word[1]=... //character string char word[]={'h','e','l','l','l','\0'}; this\0 That's what makes this word Is a string. Although it is still a character array, it can be used as a string for operation
character string
'\ 0' and '0' are different, '0' represents ASCII zero, and '\ 0' represents 0
//String variable char *str="hello"; char word[]="hello"; char line[10]="hello"; //string constant example: "hello" 1."hello"The compiler will turn it into a character array and put it somewhere. The length of this array is 2.The degree is 6 and there is a 0 at the end 3.Two adjacent string constants are automatically concatenated //character string 1.C Language strings exist in the form of character arrays 2.You cannot operate on a string with an operator 3.You can traverse strings through arrays 4.The only special thing is that string literals can be used to initialize character arrays 5.And the standard library provides a series of string functions
40. String constant
char* s="hello world";
1.s is a pointer initialized to point to a string constant
2. Because of the location of this constant, s is actually const char* s, but for historical reasons, the compiler accepts the writing method without const
3. However, trying to write to the string referred to by s will lead to serious consequences
4. If you need to modify the string, you should use array
char s[]="hello world";
Pointer or array?
1.char *str="hello";
2.char str[]="hello";
3. Array: this string is here
Space is automatically reclaimed as a local variable
4. Pointer: I don't know where this string is
Is to express a string, read-only, do not write
Processing parameters
Dynamically allocate space
NOTE:
If you want to construct a string - > array
If you want to process a string - > pointer
char*Is a string 1.A string can be expressed as char*Form of 2.char*Not necessarily a string Originally meant to be a pointer to a character, it may point to an array of characters (like int*Same) 3.Only if the character array it refers to has an ending 0, it can be said that it refers to a string
41. String input and output
/* char string[8]; scanf("%s",string); printf("%s",string); scanf Read in a word (until space, tab or enter) scanf It is not safe because the length of the content to be read is not known char string[8]; scanf("%7s",string);//Tell the machine to read up to 7 characters, and don't use more than 7 characters */ #include<stdio.h> #include<string.h> void f(){ char str1[8]; char str2[8]; scanf("%7s",str1); scanf("%7s",str2); printf("%s##%s\n",str1,str2); } int main(){ f(); return 0; } //Output results 12345678 1234567##8 /* Secure input char string[8]; scanf("%7s",string); 1.The number between% and s indicates the maximum number of characters allowed to be read. This number should be 1 less than the size of the array 2.Where does the next scanf start? Common errors char* string;//It means that a pointer variable string is defined scanf("%s",string); 1.Assuming that char * is a string type, you can use it directly by defining a variable string of string type 2.Since string is not initialized to 0, it is not necessary to make an error every time Empty string 1.char buffer[100]=""; This is an empty string, buffer[0]==' buffer [0] = = '\ 0'' 2.char buffer[]=""; The length of this array is only 1! */
42. String array
/* 1.char **a a Is a pointer to another pointer that points to a character (string) 2.char a[][] char a[][10];//It means a [0] -- > char [10] each array element is a string with a character length of 10 char a[][10]={ "hello", "world", "python" }; 3.Another way of writing is char *a[]={ "hello", "world", "python" }; A [0] - > char* */
43. Single character input and output
/* putchar 1.int putchar(int c); 2.Write a character to standard output 3.EOF(-1) indicates write failure getchar 1.int getchar(void); 2.Read a character from standard input 3.The return type is int to return EOF(-1) 4.windows--->Ctrl-z unix--->Ctrl-D */ #include<stdio.h> int main(){ int ch; while((ch=getchar())!=EOF){ putchar(ch); } return 0; }
44. String function strlen
/* string.h 1.strlen 2.strcmp 3.strcpy 4.strcat 5.strchr 6.strstr strlen 1.size_t strlen(const char*s); 2.Returns the string length of s (excluding the ending 0) */ #include<stdio.h> #include<string.h> int main(){ char str[]="hello"; printf("%lu\n",strlen(str)); printf("%lu\n",sizeof(str)); return 0; } //Output results 5 6 /* strcmp 1.int strcmp(const* char *s1,const char* s2); 2.Compare two strings and return: 0:s1==s2 1:s1>s2 -1:s1<s2 */ /* strcpy 1.char *strcpy(char *restrict dst,const char* restrict src);//The purpose comes first and the source comes later 2.Copy the src string to dst restrict Indicates that src and dst do not overlap (C99) 3.Return to dst In order to chain the code //Copy a string char *dst=(char*)malloc(strlen(src)+1); strcpy(dst,src); */ #include<stdio.h> #include<stdlib.h> char *mypy(char *dst,const char *src){ int idx=0; //Array version while(src[idx]){ dst[idx]=src[idx]; idx++; } dst[idx]='\0'; //Pointer version /* char *ret=dst; while(*src){ *dst=*src; dst++; src++; } *dst='\0'; return ret;*/ } int main(){ char s1[]="abc"; char s2[]=""; mypy(s2,s1); printf("%s\n",s2); return 0; } //Output results abc /* strcat 1.char* strcat(char *restrict s1,const char*restrict s2); 2.Copy s2 to the back of s1 and then make a long string 3.Return to s1 4.s1 There must be enough space safety problem strcpy And strcat may have security problems If the destination doesn't have enough space? It is recommended not to use these two functions whenever possible Secure version 1.char * strncpy(char *restrict dst,const char* restrict src,size_t n); 2.char *strncat(char* restrict s1,const char *restrict s2,size_t n); 3.int strncmp(const char *s1,const char *s2,size_t n);//This function is to compare the first n */
45. String search function
/* Character not found in string char *strchr(const char* s,int c);//Look on the left char *strrchr(const char* s,int c);//Look on the right NULL is returned to indicate that it was not found How to find the second one? */ #include<stdio.h> #include<string.h> int main(){ char s[]="hello"; char *p=strchr(s,'l'); p=strchr(p+1,'l'); printf("%s\n",p); return 0; } //Output results lo #include<stdio.h> #include<string.h> int main(){ char s[]="hello"; char *p=strchr(s,'l'); char *t=(char*)malloc(strlen(p)+1); p=strchr(p+1,'l'); t=strcpy(t,p); printf("%s\n",t); return 0; } //Output results lo #include<stdio.h> #include<string.h> int main(){ char s[]="hello"; char *p=strchr(s,'l'); char c=*p; *p='\0'; char *t=(char*)malloc(strlen(s)+1); p=strchr(p+1,'l'); t=strcpy(t,s); printf("%s\n",t); free(t); return 0; } //Output results he /* String not found in string char *strstr(const char *s1,const char* s2); char *strcasestr(const char *s1,const char *s2);//Ignore case to find */
46. Enumeration
/* 1.Enumeration is a user-defined data type, which is declared with the keyword enum in the following syntax enum Enumeration type name {name1,name2,...,name3}; 2.Enum type names are usually not really used, but names in braces should be used, because they are constant symbols, their type is int, and their values range from 0 to n. For example: enum colors{red,yellow,green}; 3.In this way, three constants are created. The value of red is 0, yellow is 1, and green is 2 4.When you need some constant values that can be arranged, the meaning of defining enumeration is to give these constant values names. */ #include<stdio.h> enum color{red,yellow,green};//It is equivalent to defining a color variable type. In fact, red, yellow and green are equivalent to int types void f(enum color c); int main(){ enum color t=red;//Define a variable t of color type and assign red to T. This enum cannot be omitted in C language and can be omitted in C + + scanf("%d",&t); f(t); return 0; } void f(enum color c){ printf("%d\n",c); } //Routine: enumeration of automatic counting #include<stdio.h> enum COLOR{RED,YELLOW,GREEN,NumCOLORS}; int main(){ int color=-1; char *ColorNames[NumCOLORS]={"red","yellow","green"}; char *colorName=NULL; printf("Please enter your favorite color code:"); scanf("%d",&color); if(color>=0&&color<NumCOLORS){ colorName=ColorNames[color]; }else{ colorName="unknown"; } printf("What color do you like%s\n",colorName); return 0; } //Output results Please enter your favorite color code: 0 What color do you like red /* Enumerator 1.You can specify a value when declaring an enumerator 2.enum COLOR{RED=1,YELLOW,GREEN=5}; */ #include<stdio.h> enum COLOR{RED=3,YELLOW,GREEN=5}; int main(){ printf("GREEN=%d\n",GREEN); return 0; } //Output results GREEN=5 /* Enumeration is just int 1.Although enumeration types can be used as types, they are rarely used, which can be said to be difficult to use 2.If there is a meaningful parallelism of names, enumeration is more convenient than const int 3.Enumerations are better than macro s because enumerations have int types */
47. Type of structure
struct date{ int month; int day; int year; }; //Don't forget the last semicolon /* Form of declaration structure: the first form struct point{ int x; int y; }; struct point p1,p2; p1 And p2 are both point s, which have the values of x and y The second form: struct{ int x; int y; }p1,p2; p1 And p2 are nameless structures with x and y inside The third form: struct point{ int x; int y; }p1,p2; p1 And p2 are both point s with values of x and y */ #include<stdio.h> struct date{ int month; int day; int year; }; int main(){ //The first initialization method struct date today={07,31,2021}; //The second initialization method struct date thismonth={.month=7,.year=2021}; printf("today's date is %i-%i-%i.\n",today.month,today.day,today.year); printf("this month is %i-%i-%i.\n",thismonth.year,thismonth.month,thismonth.day); return 0; } //Output results today's date is 7-31-2021. this month is 2021-7-0.
Structure member
1. The structure is a bit like an array
2. The array uses [] operation to match the subscript to access its members
a[0]=10;
3. Structure uses. Operator and name to access its members
today.day
student.firstName
p1.x
p1.y
Structural operation
1. To access the whole structure, directly use the name of the structure variable
2. For the whole structure, you can assign values, take addresses, or pass them to function parameters
p1=(struct point){5,10};// Equivalent to p1.x=5;p1.y=10;
p1=p2;// Equivalent to p1.x=p2.x;p1.y=p2.y;
Structure pointer
1. Different from array, the name of structure variable is not the address of structure variable, and the & operator must be used
2.struct date *pDate=&today;
48. Structure and function
/* Structure as function parameter int numberOfDays(struct date d) 1.The entire structure can be passed into the function as the value of the parameter 2.At this time, create a new structure variable in the function and copy the value of the caller's structure 3.You can also return a structure 4.This is completely different from arrays Input structure 1.There is no direct way to scanf one structure at a time 2.If we're going to write a function to read in the structure 3.-> 4.But how can the read structure be sent back? 5.Remember that C passes values when a function is called So p in the function is different from y in main After the function reads the value of p, nothing returns to main, so y is still {0,0} */ #include<stdio.h> struct point{ int x; int y; }; void getstruct(struct point); void output(struct point); int main(){ struct point y={0,0}; getstruct(y); output(y); return 0; } void getstruct(struct point p){ scanf("%d",&p.x); scanf("%d",&p.y); printf("%d,%d",p.x,p.y); } void output(struct point p){ printf("%d,%d",p.x,p.y); } //Output results 1 2 1,20,0 /* Solutions 1.In the previous scheme, a structure is passed into the function and then operated in the function, but it does not return The problem is that the outer clone is passed into the function, not the pointer The incoming structure is different from the incoming array 2.In this input function, you can create a temporary structure variable and return the structure to the caller */ #include<stdio.h> struct point{ int x; int y; }; struct point getstruct(void); void output(struct point); int main(){ struct point y={0,0}; y=getstruct(); output(y); return 0; } struct point getstruct(void){ struct point p; scanf("%d",&p.x); scanf("%d",&p.y); printf("%d,%d",p.x,p.y); return p; } void output(struct point p){ printf("%d,%d",p.x,p.y); } //Output results 1,2 1,21,2 /* Structure pointer as parameter Pointer to structure struct date{ int month; int day; int year; }myday; struct date *p=&myday; (*p).month=12; p->month=12; Use - > to represent the member of the structure variable indicated by the pointer */ //Modify the above procedure #include<stdio.h> struct point{ int x; int y; }; struct point *getstruct(struct point *y); int main(){ struct point p={0,0}; getstruct(&p); print(&p); output(p); return 0; } struct point *getstruct(struct point *y){ scanf("%d",&y->x); scanf("%d",&y->y); printf("%d,%d\n",y->x,y->y); return y; } //Because the print function only outputs the value and does not modify it, const can be added void print(const struct point *y){ printf("%d,%d\n",y->x,y->y); } void output(struct point p){ printf("%d,%d\n",p.x,p.y); } //Output results 1 2 1,2 1,2 1,2
49. Structure array
struct date dates[100];
struct date dates[]={
{4,5,2005},{2,4,2005}};
#include<stdio.h> struct time{ int hour; int minutes; int seconds; }; struct time timeUpdate(struct time now); int main(){ struct time testTimes[5]={ {11,59,59},{12,0,0},{1,2,3},{4,5,6},{6,7,8} }; int i; for(i=0;i<5;i++){ printf("Time is %.2i:%2i:%2i",testTimes[i].hour,testTimes[i].minutes,testTimes[i].seconds); testTimes[i]=timeUpdate(testTimes[i]); printf("...one second later it's %.2i:%.2i:%.2i\n",testTimes[i].hour,testTimes[i].minutes,testTimes[i].seconds); } return 0; } struct time timeUpdate(struct time now){ ++now.seconds; if(now.seconds==60){ now.seconds=0; ++now.minutes; if(now.minutes==60){ now.minutes=0; ++now.hour; if(now.hour==24){ now.hour=0; } } } return now; } //Output results Time is 11:59:59...one second later it's 12:00:00 Time is 12: 0: 0...one second later it's 12:00:01 Time is 01: 2: 3...one second later it's 01:02:04 Time is 04: 5: 6...one second later it's 04:05:07 Time is 06: 7: 8...one second later it's 06:07:09
/* Structure in structure struct dateAndTime{ struct date sdate; struct time stime; }; Nested structure struct point{ int x; int y; }; struct rectangle{ struct point pt1; struct point pt2; }; If there are variables struct rectangle r; You can have r.pt1.x r.pt1.y r.pt2.x r.pt2.y If there is a variable definition: struct rectangle r,*rp; rp=&r; Then the following four forms are equivalent: r.ptl.x rp->ptl.x (r.ptl).x (rp->prl).x But there is no RP - > ptl - > x, because ptl is not a pointer */ //An array of structures in a structure #include<stdio.h> struct point{ int x; int y; }; struct rectangle{ struct point p1; struct point p2; }; void printRect(struct rectangle r){ printf("<%d,%d> to <%d,%d>\n",r.p1.x,r.p1.y,r.p2.x,r.p2.y); } int main(){ int i; struct rectangle rects[]={ {{1,2},{3,4}},{{3,4},{5,6}} }; for(i=0;i<2;i++){ printRect(rects[i]); } return 0; } //Output results <1,2> to <3,4> <3,4> to <5,6>
50. Type definition
/* Custom data type 1.C The language provides a function called typedef to declare a new name for an existing data type. For example: typedef int Length; Make Length an alias of type int. In this way, the name Length can appear in the variable definition and parameter declaration instead of int: Length a,b,len; Length numbers[10]; typedef 1.Declare the name of the new type The new name is some kind of alias The readability of the program is improved typedef long int64_t; typedef struct ADate{ int month; int day; int year; }Date;//Date It represents everything between typedef and Date int64_t i=100000000; Date d={9,1,2005}; typedef typedef int Length;//Length It is equivalent to int type typedef *char[10] Strings;//Strings Is the type of an array of 10 strings typedef struct node{ int data; struct node*next; }aNode; or typedef struct node aNode;//In this way, arnode can replace struct node */
51. United Nations
slightly
52. Global variables
1. Variables defined outside the function are global variables
2. The global variable has a global lifetime cooperation domain
They are independent of any function
They can be used inside any function