Learning a programming language is a road that is both difficult and happy. Now that you have chosen this road, you should keep going and understand the basic knowledge of C language. You must first have a general understanding of C language. Let me introduce it below. Basics of C language.
1. What is C language.
#include <stdio.h>
int main()
{
printf("Hello\n");
printf("Just do it!\n");
return 0;
}
Print the result:
There is \n (this is the newline operator, which will be introduced below)
None\n
2.1 #include <stdio.h> : Every C language program code contains a header file. include is called the file inclusion command, and its meaning is to include the files specified in angle brackets <> or quotation marks "" into the program. , become part of this program. The included file is usually provided by the system, and its extension is .h, and stdio is the abbreviation of standard input output, which means "standard input and output". It is in a fixed format in the program and can be input.
2.2 int main() : The main function is the entrance to the program. There is only one main function in a project. It is a way of declaring the main function in C language. There is a pair of {} under int main(), in which the code is entered. .
2.3 printf : Indicates the result to be output. The result is placed within double quotes in (" "). If a certain character type needs to be printed in particular, the general format is ("Data type to be printed\n " , the data type to be output Variable ) The blue part represents the fixed format. The green part indicates the different things that need to be input when printing the corresponding content. \n indicates line breaks, which are optional. Only the different formats of the printed results do not affect the printed content. The specific types that need to be printed are shown below.
2.4 return 0 : The return value is 0. We won’t go into details yet. Just record it in a fixed format and type it in.
Note: Each statement needs to be followed by a semicolon under English input;
3. Data type
#include <stdio.h>
int main()
{
printf("%d\n", sizeof(char));
printf("%d\n", sizeof(short));
printf("%d\n", sizeof(int));
printf("%d\n", sizeof(long));
printf("%d\n", sizeof(long long));
printf("%d\n", sizeof(float));
printf("%d\n", sizeof(double));
printf("%d\n", sizeof(long double));
return 0;
}
In the code, %d prints an integer type, and sizeof() is used to print the size of the data type.
Print the result:
The numerical size represents the space size of various data types. The unit is byte (byte) 1GB=1024MB 1MB=1024KB 1KB=1024byte 1 byte=8 bits. The bit: is a bit in binary data, abbreviated as b , transliterated as bit, is the smallest unit of computer storage data.
4. Constants and variables
int age = 150;
float weight = 45.5f;
char ch = 'w';
Select the type of variable that needs to be defined (int, char, float, etc.), give the variable a corresponding variable name (you can define it flexibly, it is best to facilitate your own memory, for example, when you need to assign a value to age, use age as the variable name), and use = to proceed. When assigning a value, place the value after the equal sign and a semicolon as usual.
4.2 Classification of variables
Global variables: defined outside int main(), valid for the entire code
Local variables: Define an area enclosed by { } within a certain scope. When it goes out of the scope, it is invalid. If global variables and local variables exist together, local variables take precedence.
#include <stdio.h>
int b = 2020; //全局变量
int main()
{
int b = 2021; //局部变量
int c = 2022; //局部变量
printf("b = %d\n", b);
return 0;
}
Print the result:
4.3 Use of variables
Let’s take the example of calculating the sum of two numbers
#include <stdio.h>
int main()
{
int num1 = 0;
int num2 = 0;
int sum = 0;
printf("输入两个操作数:>");
scanf("%d %d", &num1, &num2);
sum = num1 + num2;
printf("sum = %d\n", sum);
return 0;
}
Enter two random numbers
In the code, first define the two digital integer types that need to be input, int num1=0; int num 2=0; assign an initial value of 0, and then define a variable to store the value that needs to be output, int sum=0; put the initial value in both 0; First output a prompt and enter two operands:> Use scanf ("%d %d", &num1, &num2) to find the addresses of variables num1 and num2 to achieve the purpose of assigning values to variables at any time, sum=num1+num2 Define the algorithm, that is, find the sum of two numbers, use the variable sum to take over the result, and finally use printf to output the value of sum.
4.5 Constants
The definition forms of constants and variables in C language are different.
1. Literal constant: known value
2.const modified constant variable: has a fixed effect on the assigned variable and cannot be changed subsequently.
#include <stdio.h>
int main()
{
const int num = 4;
printf("%d\n", num);
int num = 8;//此处对num再赋值已经无效了
printf("%d\n", num);
return 0;
}
Among them, the const-modified constant variable has a fixed effect on the assigned sum, and subsequent assignment to num will have no effect. Although num is assigned a fixed value, the essence of num is still a variable, but it has the nature of a constant. The verification is as follows:
#include <stdio.h>
int main()
{
const int n = 10;
int arr[n] = { 0 };//数组[]中需要的是一个常量,虽然const修饰的n有常属性,但是他的本质是一个变量所以有错误
return 0;
}
So there is no output:
3. Identifier constant defined by #define: The defined identifier does not occupy memory and is just a temporary symbol. This symbol will no longer exist after precompilation. For example: the assignment to MAX is defined outside the main function.
#include <stdio.h>
#define MAX 10
int main()
{
int arr[MAX]={0};
printf(" %d\n", MAX);
return 0;
}
4. Enumeration constants: They need to be listed one by one, and the enumeration keyword enum needs to be used. Those placed in the enumeration are called enumeration constants.
#include<stdio.h>
enum people
{
KID,
MAN,
WOMAN,
}; //其中KID,MAN,WOMAN,叫做枚举常量
int main()
{
printf("%d\n", KID);
printf("%d\n", MAN);
printf("%d\n", WOMAN);
return 0;
}
5. String + escape character + comment
#include <stdio.h>
int main()
{
printf("Hello\n");
printf("Just do it!\n");
return 0;
}
escape character | Definition |
\0 | end sign |
\? |
Used when writing multiple question marks in a row to prevent them from being parsed into three-letter words
|
\' |
used to represent character constants
'
|
\" |
Used to represent double quotes inside a string
|
\\ |
Used to represent a backslash, preventing it from being interpreted as an escape sequence character.
|
\a |
Warning character, buzzer
|
\b |
backspace character
|
\f |
paper feed character
|
\n |
newline
|
\r |
Enter
|
\t |
horizontal tab
|
\v |
vertical tab
|
\ddd |
ddd
represents
1 to 3
octal digits. Such as:
\130
|
\xdd |
dd
represents
2
hexadecimal digits. Such as: \x30
|
1. Let me first introduce you to the end mark\0
#include<stdio.h>
int main()
{
char arr1[] = "bit";
char arr2[] = { 'b', 'i', 't' };
char arr3[] = { 'b', 'i','t', '\0' };
printf("%s\n", arr1);
printf("%s\n", arr2);
printf("%s\n", arr3);
return 0;
}
Print the result:
When the string is placed in the array, a \0 will be entered at the end by default. That is to say, in the array char arr1 [ ]={"bit"}, the contents actually included are 'b', 'i', 't' , '\0', so it ends after printing the bit. However, when a single character such as array char arr2 [ ]={'b', 'i', 't'} is entered, \ will not be entered by default at the end. 0, so after printing the bit, the printing does not end, but some random values are printed. Therefore, there are some "hot, hot, hot, hot, hot, it". If you manually enter \0 at the end, you will manually give an end mark, such as the array char arr3 [ ]={'b' , 'i', 't', '\0'}, if the bit encounters \0 after printing, then the printing will end.
2. Escape character \?: Used when writing multiple consecutive question marks to prevent them from being parsed into three-letter words. Three-letter words exist in older versions of the compiler.
#include<stdio.h>
int main()
{
printf("(are you ok\?\?)\n");// \?在书写连续多个问号时使用,防止他们被解析成三字母词
return 0;
}
Print the result:
3. Escape characters \' and \": simply to output single quotes and double quotes
#include<stdio.h>
int main()
{
printf("\'");
printf("\"");
return 0;
}
![](https://img-blog.csdnimg.cn/c7370542eba64a9ba43934e5acdd1b5e.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAUmlzaW5nLXBlcnNvbg==,size_20,color_FFFFFF,t_70,g_se,x_16)
#include<stdio.h>
int main()
{
printf("a\ta");
return 0;
}
Output result:
#include<stdio.h>
int main()
{
printf("\101\n");
printf("\x42");
return 0;
}
Output result:
#include<stdio.h>
int main()
{
printf("c:\\test\41\test.c");
return 0;
}
Output result:
Among them, \t is called a horizontal tab character, which is equivalent to a space position with a tab key. In order to prevent \t from being recognized as an escape character, \\ is specified as a backslash to prevent it from being interpreted as an escape character. Double negation has almost the same meaning as affirmation. The octal number \41 is converted to decimal 33, and the corresponding ASCII code character is! , other characters are printed directly without escape characters.
7. Escape character \a: warning character, buzzer
#include<stdio.h>
int main()
{
printf("\a");
return 0;
}
There will be a "ding dong" sound when printing.
8. Escape character \b: backspace character
#include<stdio.h>
int main()
{
printf("abcdef\b\b\b\b");
return 0;
}
Print the result:
\b means backspace. When you retreat to the corresponding position, the corresponding character will not be printed. There is a superposition effect when backspace. In the above code, a total of 4 \bs are entered, and the corresponding characters are backwards 4 spaces. In the input abcdef The fourth last digit c will not print
9. Escape character \f: page change, moves the current position to the beginning of the next page. When using the printer, the page will be changed directly, which is not obvious in the compiler.
10. Escape character \v: vertical tab character, also used when printing
11. Escape character \r: carriage return, moves the current position to the beginning of this line, and overwrites printing
#include<stdio.h>
int main()
{
printf("abcdef\r");
return 0;
}
Print the result:
5.3 Notes: 1. If there are unnecessary codes in the code, you can delete them directly or comment them out.
Take using a function to calculate the sum of two numbers as an example:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int Add(int x, int y)
{
return x + y;
}
/*C语言风格注释
int Sub(int x, int y)
{
return x-y;
}
*/
int main()
{
int a = 0;
int b = 0; //C++注释风格
scanf("%d%d", &a, &b); //用scanf取a,b的地址,能够随机赋值计算
printf("sum=%d\n", Add(a, b)); //调用Add函数,完成加法
return 0;
}
Print the result:
6. Selection statement: implemented with if statement and switch case statement
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int num = 0;
printf("学习编程\n");
printf("你能够坚持吗?(0不能/1能)");//>:为提示符
scanf("%d", &num);
if (1==num)
printf("好工作,高薪资");
else
printf("平淡的生活");
return 0;
}
7. Loop statements: implemented using while statements , for statements, do... while statements
Some things must be done all the time, such as studying, which should be done day after day
For example, use while to continuously input numbers from 1 to 100:
#include<stdio.h>
int main() //代码功能:输出1-100的数字
{
int a = 1;
//int b = 0;
while (a < 101)
{
printf(" %d", a );
a += 1;
}
return 0;
}
Print the result:
8. Function: It is to simplify the code and reuse the code.
8.1 Library functions: When we describe basic functions, they are not business code. Every programmer may use it during our development process. In order to support portability and improve program efficiency, the basic library of C language provides a series of similar library functions to facilitate programmers to develop software. like:
8.2 Custom functions: If the library function can do everything, then there is no need for programmers. What is more important is the custom function . The custom function has the same function name, return value type and function parameters as the library function. But the difference is that we design these ourselves. This gives programmers a lot of room to play.
For example, calculate the sum of two numbers:
#include <stdio.h>
int main()
{
int num1 = 0;
int num2 = 0;
int sum = 0;
printf("输入两个操作数:>");
scanf("%d %d", &num1, &num2);
sum = num1 + num2;
printf("sum = %d\n", sum);
return 0;
}
Use a function to calculate the sum of two numbers:
#include <stdio.h>
int Add(int x, int y)
{
int z = x+y;
return z;
}
int main()
{
int num1 = 0;
int num2 = 0;
int sum = 0;
printf("输入两个操作数:>");
scanf("%d %d", &num1, &num2);
sum = Add(num1, num2);
printf("sum = %d\n", sum);
return 0;
}
Directly call the self-defined function int Add(int x, int y), so you don’t need to type the code repeatedly. When you need to find the sum of two numbers, just call the function directly.
9. Array
9.1 Definition: A set of elements of the same type
Example: How to store numbers from 1 to 10 ?
int arr[10] = {1,2,3,4,5,6,7,8,9,10};//定义一个整形数组,最多放10个元素
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
//如果数组10个元素,下标的范围是0-9
The subscript corresponding to each value in the array:
Print the values in the array:
#include <stdio.h>
int main()
{
int i = 0;
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
for(i=0; i<10; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Print the result:
10. Operators: arithmetic operators, shift operators, bit operators, assignment operators
10.1 Arithmetic operators: + - * (multiplication sign) / (division sign) % (remainder)
1. In addition to the % operator, several other operators can operate on integers and floating-point numbers.
2. For the / operator, if both operands are integers, perform integer division. As long as there are floating point numbers, floating point division is performed.
3. The two operands of the % operator must be integers. Returns the remainder after division.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int a = 0;
int b = 1; //对b赋的初始值不能为0,因为在后面要作为除数
int c = (-8 + 22) * a - 10 + b / 2;
int d = a % b;
scanf("%d%d", &a, &b);
printf("计算结果=%d\n", c);
printf("取余=%d\n", d);
return 0;
}
Print the result:
10.2 Shift operators: <<Left shift operator >>Right shift operator
1. The operand of the shift operator can only be an integer.
2. It is aimed at shifting the binary value after converting it from decimal to binary.
3. For the left shift operator, the left side is discarded and the right side is filled with zeros
. 4. For shifting Operator, do not move negative bits, this is not defined by the standard
int main()
{
int a = 1;//int型有4个字节32个比特位转化为二进制00000000000000000000000000000001 转化为十进制就为1
int b=a << 2; //00000000000000000000000000000100 转化为十进制就为4
int b=a<<-1;//错误的移位
printf("%d", b);
return 0;
}
Print the result:
The shift operator is used to shift binary numbers. For example, in the above code, 4 bytes of int type = 4x8 = 32 bits, the corresponding integer is first converted into a 32-bit binary number, and then the binary number is shifted. Bit compliance - when the left shift operator is used, the left side is rounded off and the right side is padded with zeros; when the right shift operator is used, the right side is rounded off and the left side is padded with zeros. Finally, the shifted binary number is converted into a decimal number and printed.
10.3 Bit operators: & Bitwise AND | Bitwise OR ^ Bitwise XOR (all for binary)
#include<stdio.h>
int main()
{
int a = 1; //0001
int b = 2; //0010
printf("%d\n", a & b); //0000
printf("%d\n", a | b); //0011
printf("%d\n", a ^ b); //0011 相同为0不同为1
return 0;
}
Print the result:
10.4 Assignment operators: = += -= *= /= &= ^ = |= >>= <<=
Operator | effect |
! |
logical inverse operation
|
- | negative value |
+ | Positive value |
& | Get address |
sizeof | Operand type length in bytes |
~ | Bitwise negation of the binary representation of a number |
-- | Front, rear-- |
++ | Front, rear ++ |
* | Indirect access operation fee (dereference operation method) |
(type) | cast |
The first five operators have been introduced before. I will just introduce the next five operators to you.
1. Bitwise inversion of a binary number~: ~ is a unary operator, used to invert a binary number bitwise, that is, 0 is changed to 1, and 1 is changed to 0. For example: hexadecimal 9 corresponds to: 0x00000009 When negated, ~9 corresponds to: 0xfffffff6
#include<stdio.h>
main()
{
int a = 0;
printf("%x", ~a);
}
Print the result:
2. Prefix and post++: The role of prefix ++ is to perform operations first and then assign values, while postfix ++ is to copy first and then perform operations.
Prefix++:
#include <stdio.h>
main()
{
int i = 2;
int a=++i;
int b = i;
printf("a=%d\n", a);
printf("b=%d\n", b);
}
Print the result:
In the code, we first give i an initial value of 2, and use b to reflect the final value of i. Prefix ++ first performs the +1 operation on 2, and then assigns the value 3 after adding 1 to the variable a, so the value of a is 3. After the operation and assignment, the value of i becomes 3, so i changes The last value 3 is assigned to b, so the value of b is 3
Post++:
#include <stdio.h>
main()
{
int i = 2;
int a = i++;
int b = i;
printf("a=%d\n", a);
printf("b=%d\n", b);
}
Print the result:
In the code, we first give i an initial value of 2, and use b to reflect the final value of i. Postfix ++ is to first assign the value 2 of i to a, then add 1 to i, then the value of a is 2. After the assignment and operation, the value of i becomes 3, so the changed value 3 of i is assigned to b, so the value of b is 3.
3. Preposition, postposition--:
Prefix --:
#include <stdio.h>
main()
{
int i = 2;
int a = --i;
int b = i;
printf("a=%d\n", a);
printf("b=%d\n", b);
}
Print the result:
In the code, we first give i an initial value of 2, and use b to reflect the final value of i. Preposition - first performs the -1 operation on 2, and then assigns the value 1 after subtracting 1 to the variable a, so the value of a is 1. After the operation and assignment, the value of i becomes 1, so i changes The value 1 after is assigned to b, so the value of b is 1
Postfix --:
#include <stdio.h>
main()
{
int i = 2;
int a = i--;
int b = i;
printf("a=%d\n", a);
printf("b=%d\n", b);
}
Print the result:
In the code, we first give i an initial value of 2, and use b to reflect the final value of i. Postposition-- the value 2 of i is first assigned to a, and then i is subtracted by 1, then the value of a is 2. After the assignment and operation, the value of i becomes 1, so the changed value 1 of i is assigned to b, so the value of b is 1.
4. Indirect access operation fee (dereference operation method) *: This operator is often used for pointers
#include<stdio.h>
int main()
{
int a = 10;
int* p= &a;
*p =20;
printf("%d\n", a);
return 0;
}
Print the result:
If you want to understand this code, you need to first understand the concept of pointers. You can scroll down first to get a preliminary understanding of pointers. *p=20 in the code ; * is the dereference operator, which means to find the object pointed to by p through the address stored in p, and *p is the object pointed to by p, which represents the variable a .
5. Forced type conversion (type):
#include<stdio.h>
int main()
{
double a = 3.14;
printf("%d\n", (int)a);
return 0;
}
Print the result:
The originally defined variable is of double type. Under the forced conversion (type), the variable a is converted to the int type. When using this operator, put the type that needs to be converted into parentheses, and put the variable that needs to be converted next to it. The post-cut is only valid for one variable. If there are two variables after (), it is only valid for the first variable that follows. The conversion can only take effect in this statement, and elsewhere, the variable a is still of double type.
> | more than the |
>= | greater or equal to |
< | less than |
<= | less than or equal to |
!= | Used to test "inequality" |
== | Used to test "equality" |
&& | logical AND |
|| | logical or |
11. Common keywords: C language provides a wealth of keywords. These keywords are preset by the language itself. Users cannot create keywords themselves.
#include(stdio.h)
#define c 100
int main()
{
printf("%d\n", c);
int d = 100;
printf("%d", d);
return 0;
}
打印结果:
12.2 #define 定义宏:
#include<stdio.h>
#define add(x,y)(x)+(y) //宏名 参数 宏体
int main()
{
int a = 10;
int b = 20;
int c = add(a, b); //替换成int c=((a)+(b))
printf("%d", c);
return 0;
}
打印结果:
十三、 指针
13.1 想了解指针需要先了解一下内存:内存是电脑上特别重要的存储器,计算机中程序的运行都是在内存中进行的 。 所以为了有效的使用内存,就把内存划分成一个个小的内存单元,每个内存单元的大小是1个字节。 为了能够有效的访问到内存的每个单元,就给内存单元进行了编号,这些编号被称为该内存单元的地址。
内存单元有相对应的编号,这一个编号就是地址,这个地址也叫做指针,也就是说地址就是指针,用来储存地址的变量叫指针变量。
如何取出变量的地址呢?就要用到前面介绍的取地址符&
#include <stdio.h>
int main()
{
int num = 10;
#//取出num的地址。注:这里num的4个字节,每个字节都有地址,取出的是第一个字节的地址(较小的地址)
printf("%p\n", &num);//打印地址,%p是以地址的形式打印
return 0;
}
&num的作用就是取出创建的变量num的地址
内存 | |
一个字节 | 0xFFFFFFFF |
一个字节 | 0xFFFFFFFE |
一个字节 | 0xFFFFFFFD |
0x0012FF47 | |
0x0012FF46 | |
0x0012FF45 | |
0x0012FF44 | |
一个字节 | 0x00000002 |
一个字节 | 0x00000001 |
一个字节 | 0x00000000 |
变量num的类型是int类型,其大小为4个字节,红色的部分为num的地址,打印的地址就是读取到num的第一个地址。
变量取出来后如果需要储存,就需要定义指针变量:
int num = 10;
int* p=&num; //int说明指针变量p所指的变量num是一个整形
指针的具体使用:
#include<stdio.h>
int main()
{
int a = 10;
int* p= &a;
*p =20;
printf("%d\n", a);
return 0;
}
打印结果:
#include<stdio.h>
int main()
{
printf("%d\n", sizeof(char *));
printf("%d\n", sizeof(short *));
printf("%d\n", sizeof(int *));
printf("%d\n", sizeof(double *));
return 0;
}
打印结果:
结论:指针大小在32位平台是4个字节,64位平台是8个字节。
#include<stdio.h>
struct xs //定义结构体类型要用struct,这个类型名叫xs(自己定义)
{
char name[20]; //叫做结构体成员,其中要放的是字符串,需要将字符串放到字符串数组里面
int age ;
char sex[10];
char id[15];
};
void project(struct xs* dy) //自定义函数project,将s的地址赋给dy,*dy表示的是s
{
printf("%s %d %s %s\n", (*dy).name, (*dy).age, (*dy).sex, (*dy).id);
printf("%s %d %s %s\n", dy->name, dy->age, dy->sex, dy->id);
}
int main()
{
struct xs s = { "张三", 21 ," 男 ","20209999" };//s为创建的结构体变量,访问其对象时,需要加.这个操作符
printf("%s %d %s %s\n", s.name, s.age, s.sex, s.id);
project(&s); //自定义函数,取s的地址给自定义的函数
return 0;
}
Print the result:
The three printing methods of the structure are shown above. The one placed inside the project() function uses pointers to print, and the outside one prints directly without creating a pointer. The printing method inside the function is not much different from the one outside.
Outside the function: When printing, fill in the type that needs to be printed, and finally write the structure variable (s) at the end. The variable name of the string (name, age, sex, id) is printed in this format.
Within the function: Replace the structure variable name with a pointer, which only changes the form, but does not change the essence. Finally, change the operator "." to "->".