当前位置:网站首页>C language learning
C language learning
2022-07-21 19:38:00 【Han Piye】
Record your study C The process of language , Share good learning materials .
List of articles
Learning materials
name | type | describe | link |
---|---|---|---|
C Primer Plus | Books | ing , But there are many contents , Suitable for systematic learning | Baidu cloud ,u46k |
C Language programming | Books | Be concise | link |
This study mainly refers to the above resources .
learning environment
Recommended use in learning stage : Lesser panda devc
.c The file is preprocessed 、 compile 、 The executable program can only be generated after assembly and linking , And the integrated environment ( Lesser panda devc) It can automatically help us deal with these processes .
- Preprocessing : Refers to deleting comments 、 Replace macros and process preprocessing instructions (#include)
- compile : Refers to the pretreated c Translation of language code into sink code
- assembly : It refers to translating assembly code into machine code ( Take the place , I don't know where to call external functions and global variables )
- link : Link according to the machine code , Find the specific location
data type
Variable naming conventions
have access to Case letters 、 Underline and numbers , But the first character cannot be a number , It feels like it's for the convenience of compiler design :)
Besides , You cannot use keywords and reserved words as variable names .
- Constant : All capitals , Separate it with an underline
- Variable name : All lowercase , Separate it with an underline
Basic data type
- integer :short、int、long、long long
- floating-point :float、double、long double
- Character :char
Hexadecimal said
Base number | The number | Decimal number | IO Symbol |
---|---|---|---|
Binary system | 0b11 | 3 | - |
octal | 011 | 9 | %o |
Hexadecimal | 0x11 | 17 | %x |
Type conversion
- Implicit type conversion ( There will be no problem converting to a wide range , Conversion to a small range will be lost )
- Arithmetic conversion : Promote to the highest level in the expression
- Assignment conversion 、 Parameter passing and return values : Floating point numbers to integers discard decimal parts ; large-scale ⇒ Small areas may overflow ;
- Display type conversion : Used to prevent overflow ((long long)1000000*1000000)
Type size
sizeof value; // Acting on variables
sizeof(char); // Use parentheses on types
Life cycle & Scope
- local variable : The life cycle is code block
- Static variables : Always there , But not visible outside the code block
- Global variables : Always there , Whole
.c
so
The type definition
typedef int ID; // Define a new type
expression
Operator :+、 -、 *、 /、 %
Compare algorithms :<、 >、<=、 >=、==、!=
Logical operator :||、 &&
Self increasing 、 Self reduction :a++ ++a a-- --a
Triple operator : expression 1? expression 2: expression 3
Short-circuit operation : For logical operators &&
and ||
It has the effect of short circuit
Comma expression : Often used to declare variables
Control statement
if system 、swtich、for、while and do-while
Array
One dimensional array
#define N 1000 // Use with arrays
// Not initialized
int a[N];
// initialization
int a[N] = {
0}; // The insufficient part will be used 0 fill
int a[] = {
0, 1, 2, 3}; // from {} The value in determines the size of the array
Two dimensional array
#define N 100
// Not initialized
int a[N][N];
// initialization
int a[2][2] = {
{
0, 1}, {
2, 3}};
int a[2][2] = {
0, 1, 2, 3}; // One dimensional form initialization ( Not recommended )
int a[2][2] = {
0} // The lack of fill 0( Recommend this Qing 0)
Variable length array It feels like a fake :)
int n = 10;
int a[n]; // You can use variables to specify the length
character string
initialization
char s[] = "ni hao"; // amount to char s[] = {'n', 'i', ' ', 'h', 'a', 'o', '\0'}, You can modify
char *s = "ni hai"; // s Point to string constant , Do not modify
Common functions
int strlen(char *s);
int flag = strcmp(char *s0, char *s1);
strcpy(char *s0, char *s1);
strcat(char *s0, char *s1);
function
Function declaration & Function definition
// Function declaration
int add(int a, int b);
// Function definition
int add(int a, int b)
{
return a + b;
}
Scope of action
When a function is static When decorating , This function can only be used by this .c File access , It can reduce name pollution .
Variable length parameter
Compiler cooperation is required , The single parameter list is
#include <stdio.h>
#include <stdarg.h>
void show(int num, ...){
va_list ap;
va_start(ap, num);
for(int i=0; i<num; i++)
printf("%d\n", va_arg(ap, int));
va_end(ap);
}
int main()
{
show(4, 1, 2, 3, 4);
return 0;
}
The pointer
Save the address of the variable , It can be used to build linked lists and trees , In addition, it can reduce the cost of parameter passing during function calls .
int a = 1;
// Definition and assignment
int *p = &a;
// Can be assigned by pointer ⇒ a = 2
*p = 2;
// Pointer size (64 position --> 8)
printf("size: %d\n", sizeof (int*));
Pointer arithmetic
The pointer can add 、 Subtraction operation ( Including self increasing 、 Self reduction ), The compiler will change the value of the operation at compile time : about char *
, The compiler determines that a unit is a byte , therefore +1 After compilation, it is still +1; And for int *
, The compiler determines that a unit is four bytes , therefore +1 After compiling it into a sink code, it becomes +4.
char *p_c = 0;
int *p_i = 0;
/************************************************** The pointer carries the size information of the target :+1 For different pointers, the results are different **************************************************/
printf("%p\n", p_c); // 0
printf("%p\n", p_c+1); // 1
printf("%p\n", p_i); // 0
printf("%p\n", p_i+1); // 4
Pointers and arrays
An array is equivalent to a pointer to an immutable initialized memory area .a[1]
amount to *(a+1)
, In order to get exactly +1
It's cheap , You must know the type of the pointer .
int a[10];
int *p = a;
// Pointers can be used in array format
a[0] = 1;
printf("%d\n", *p);
printf("%d\n", p[0]); // p[0] == *(p+0) == *(a+0) == a[0]
// You cannot change the direction of the array
int b[10];
a = b; // wrong, therefore a Equivalent to int * const q = (int*)malloc(sizeof(int) * 10);
Pointers and multidimensional arrays
Want to accurately understand the relationship between multidimensional arrays and pointers , It is necessary to clarify the distribution of arrays in memory and int** And int(*)[3] The relationship between .
Distribution of memory
- python Of list It is a multi-level reference structure , top-level list Points to the sub layer list;
- C The array in is linear in memory .
int** And int (*)[3] The relationship between
Pictured above , although a、a[0]
Point to the same place , But the two data types are different .a
yes int(*)[3]
,a[0]
yes int *
, When extracting values :**a == *a[0]
, Look at it this way int** It seems to be equal to int(*)[3].
int a[2][3];
int (*p)[3] = a; // a The data type of is int (*)[3], So when receiving, it should also be of this type
int *q = a[0]; // and a[0] It is int * The type of
int b = **p; // int (*)[3] It is a special case of secondary pointer , Therefore, when taking values **
int c = *q; // q Just one *
However , There are qualitative differences between the two ,int** It's a real secondary pointer , Point to int The pointer to ; and int (*)[3] It's a bit of a fake .
int a[2][3] = {
0, 1, 2, 3, 4, 5};
int (*p)[3] = a;
printf("%p\n", p); // 000000000066FE00
printf("%p\n", *p); // 000000000066FE00, Consistent with the above , namely *p Did not visit p Memory pointed to
printf("%p\n", **p); // 0000000000000000, Only here did I really visit
Looking at the assembly code, you can find , In numerical terms ,*p
and p
The results are completely consistent , so to speak *p
Just made the data type change , Data is not accessed in the form of a general pointer . This point is similar to that mentioned above a
And a[0]
Echo with the same address value (a[0] == *(a+0)==*a
). When facing a pointer to an array ,*
The function of is to change the type , And as the type changes , Address +1
The increased offset also changes . To be specific a[1][1]
First of all 1 And the second 1 Bring different offsets . And for int**
Come on , It is really through two addressing .
Due to the above differences , When a two-dimensional array is used as a parameter , The formal parameter cannot be simply defined as int **
, And the actual transmission is int(*)[3]
Such a two-dimensional array .
Two dimensional array parameter passing
#include <stdio.h>
/******************************************************************************** there int** a Indicates that the parameter passed in is a int** The pointer , This is the closest int(*)[] The type of , However, even if It turns into void *, It's OK, too , The sizes of various pointers are consistent , The only difference is the type information attached , However, Tong Forced type conversion , This effect can be eliminated . ********************************************************************************/
void show(int **a, int n, int m)
{
int (*p)[m] = (int (*)[m]) a;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
printf("%d ", p[i][j]);
}
putchar('\n');
}
}
int main()
{
int a[2][3] = {
0, 1, 2, 3, 4, 5};
show((int **)a, 2, 3);
int b[3][4] = {
{
0, 1, 2, 3},{
4, 5, 6, 7}, {
9, 8, 7, 6}};
show((int**)b, 3, 4);
return 0;
}
macro
#define PI 3.14 // Defining constants
#define MAX(x, y) ((x)>(y)?x:y) // Macro functions : The parameter list must closely fit the macro name
/************************ Special macro __FILE__: Function name __LINE__: Lines ************************/
Conditional compilation
// Suitable for finding debug
#define DEBUG 1
#if DEBUG
// do
#endif
// fit debug
#define DEBUG
#if defined DEBUG
// do
#endif
// Abbreviation
#ifdef DEBUG
// do
#endif
// Take the opposite ( Suitable for excluding mutual inclusion )
#ifndef __MATH_H__
#define __MATH_H__
Global variables and function declarations exposed to the outside world
extern float PI;
int add(int a, int b);
#endif
Multiple files
Master the principle and practical operation of sharing global variables and functions .
// people.c: There is a global variable num_people And the function greet()
int num_people = 0;
void greet()
{
printf("Hello, boy!\n");
}
// main.c: Need to access num_people And use greet
extern int num_people; // Declare variable type , You can use this variable
void greet(); // Declare function prototypes , You can call this function
/* Declaring variable types and function prototypes is mainly to provide type checking during single file compilation , To actually get the variable address, you need to link - extern Keyword is to distinguish from variable definition ; It is not necessary to declare the function prototype - At every .c It is inconvenient to declare the type in the file , So there's a way to store statements .h writing , adopt include Copy .h file information */
structure 、 Union and enumeration
structure
// Defined struct student The type of
struct student {
int id;
char name[32];
};
struct student stu1; // Defining variables : Don't omit struct
// use typedf Simplification
typedef struct student {
int id;
char name[32];
} Student;
Student stu1 = {
12, "fyy"}; // Defining variables
printf("%d\n", stu1.id); // adopt . visit
Values * p = &stu1;
printf("%d\n", p->id); For the pointer , adopt -> visit , Equivalent to : (*p).id
union
typedef union values{
int int_v;
double double_v;
}Values;
Values v; // Pay attention to the initialization method
v.double_v = 1.234; // adopt . visit
enumeration
typdef enum size {
BIG, MIDDLE, SMALL
} Size;
Size = BIG; // Direct use
memory management
// The heap application area will not be initialized
int *arr = (int *) malloc(sizeof(int) * 100); // apply
free(arr); // Release
// Initialize the application area
int *arr = (int *) calloc(100, sizeof(int)); // Initialize to 0
// Resize
arr = (int*) realloc(arr, sizeof(int) * 200); // Resize
IO
Translate characters
Commonly used translation characters : \t
Tabulation 、\n
Line break
Blank character :\t
、 \n
、 Space
Output format
Output %: It needs to be continuous %%
Output format : according to %[ sign ][ Minimum field width ][. precision ][ Convert specifiers ]
control
- Common signs :
-
Indicates left alignment - Minimum field width : Indicates the width of the output at least ( Not enough space )
- precision : Indicates at least how many people ( Inadequate supplement 0), Integer considers all digits ; Floating point numbers only consider the number of decimal places
- Convert specifiers
type | scanf | printf |
---|---|---|
int | %d | %d |
long | %ld | %ld |
long long | %lld | %lld |
float | %f | %f |
double | %lf | %f or %lf |
char | %c | %c |
Console IO
Format input :scanf
Input matching : Understand the input of the console as a stream ( Spliced into a string ), Match according to the input format string .
- When matching the conversion specifier : When you first encounter blank characters , Skip until you encounter a non blank character , When encountering mismatched symbols , Leave the symbol in the stream , End match .
- Match blanks : You can match any number of blank characters in the input ( It can be 0 individual ).
- Match non whitespace : Direct match , If it doesn't match, exit directly , And save it for the next match .
scanf("%d%d", &a, &b);
// Input : 10\n\n20\n ⇒ a = 10, b = 20, Remaining input string : \n
// Input :10-20\n ⇒ a = 10, b = -20, Remaining input string :\n
// Input :10a20\n ⇒ a = 10, b Original value , Remaining input string :a20\n
scanf("%d %d", &a, &b);
// Input : 10\n\n20\n ⇒ a = 10, b = 20, Remaining input string : \n
// Input :10-20\n ⇒ a = 10, b = -20, Remaining input string :\n
// Input :10a20\n ⇒ a = 10, b = Original value , Remaining input string :a20\n
scanf("%da%d", &a, &b);
// Input : 10\n20\n ⇒ a = 10, b = Original value , Remaining input string : \n20\n
// Input :10a-20\n ⇒ a = 10, b = -20, Remaining input string :\n
// Input :10b20\n ⇒ a = 10, b = Original value , Remaining input string :b20\n
scanf("/%d", &a);
// Input :/1234\n ⇒ a = 1234, Remaining input string :\n
// Input :\n\n/1324\n ⇒ a = Original value , Remaining input string :\n\n/1324\n
scanf(" /%d", &a);
// Input :/1234\n ⇒ a = 1234, Remaining input string :\n
// Input :\n\n/1324\n ⇒ a = Original value , Remaining input string :\n
Format output :printf
printf("%d\n", 520); // According to the output format , Output directly .
character IO:getchar、putchar
char c = getchar(); // Enter a character
putchar(c); // Output a character
Standard streaming and redirection
C There are three standard flows , It can be used without opening or closing it .
name | meaning | equipment |
---|---|---|
stdin | The standard input | keyboard |
stdout | standard output | The screen |
stderr | The standard error | The screen |
When used cmd function exe
When you file , You can redirect files to the three standard streams mentioned above . stay cmd Input in ./run.exe <in.txt >out.txt
, At run time in.txt The data in is input as a keyboard ,out.txt Output as screen .
file IO
- Open file :
FILE * fp = fopen(path, mode);
- Close file :
fclose(fp);
- Output... To file :
fprintf(fp, Format string , ...);
- Input by file :
fscanf(fp, Format string , ...);
- To the end :
feof(fp);
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Writing documents
FILE *fp;
if((fp = fopen("test.txt", "w")) == NULL){
printf("fail to open!\n");
exit(1);
}
for(int i=0; i < 10; i++)
fprintf(fp, "%d\n", i);
fclose(fp);
// Read the file
if((fp = fopen("test.txt", "r")) == NULL){
printf("fail to open!\n");
exit(1);
}
int num;
while(fscanf(fp, "%d", &num) != EOF){
printf("%d\n", num);
}
fclose(fp);
return 0;
}
边栏推荐
- Loop structure -- while loop and do while loop
- PWM输出实验
- List container series operations (detailed)
- MySQL (2)
- armv8 DVFS
- 深度学习——(4)VGG16 图像分类
- 342个中、英文等NLP开源数据集分享
- NFS share
- Deep learning - (6) pytorch freezes the parameters of some layers
- Preparation of hemoglobin albumin nanoparticles encapsulated by Lumbrokinase albumin nanoparticles / erythrocyte membrane
猜你喜欢
随机推荐
Software test interview question: what kind of network protocol does the Internet adopt? The main hierarchy of the agreement? What protocol is used for internet physical address and IP address transla
蚓激酶白蛋白纳米粒/红细胞膜定向包裹血红蛋白-白蛋白纳米粒的研究制备
PWM输出实验
trivy 源码分析(扫描镜像中的漏洞信息)
Plantuml draw link diagram
Sorting out of high-frequency interview questions, answers and knowledge context of Android, a major Internet company in 2022
除去不必要的字段
蓝灯绿灯按时明灭,编程古鲁的密语
Installing redis in Linux
MySQL installation prompts that the application cannot start normally (0xc000007b, how to solve it?
Part I - Fundamentals of C language_ 7. Pointer
Software testing interview question: talk about your understanding of the two strategies of top-down integration and bottom-up integration in integration testing, and talk about their respective advan
Implementation method of SuperMap iclient for openlayers layer group control
Use the mogdb operator to deploy the mogdb cluster (mogdb stack) on kubernetes
FTXUI基础笔记(checkbox复选框组件)
armv8 DVFS
22张图带你深入剖析前缀、中缀、后缀表达式以及表达式求值
Sql优化(九):分页语句优化
ClickHouse深度揭秘
深度学习——(6)pytorch冻结某些层的参数