C language basics (first introduction to C language)

        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.

        C language is a general computer programming language that is widely used in low-level development. The design goal of the C language is to provide a programming language that can be easily compiled , handle low-level memory , generate a small amount of machine code , and can run without any runtime environment support.
        Although the C language provides many low-level processing functions, it still maintains good cross-platform characteristics. A C language program written in a standard specification can be compiled on many computer platforms, even including some embedded processors ( microcontrollers or (called MCU ) and supercomputers and other operating platforms.
        In the 1980s, in order to avoid differences in the C language syntax used by various developers, the American National Bureau of Standards formulated a complete set of American national standard syntax for the C language, called ANSI C , as the original standard for the C language. . [1] Currently on December 8, 2011 , the C11 standard released by the International Organization for Standardization (ISO ) and the International Electrotechnical Commission ( IEC ) is the third official standard of the C language and the latest standard of the C language. This standard is better Supports Chinese character function names and Chinese character identifiers, realizing Chinese character programming to a certain extent.
        C language is a process-oriented computer programming language, which is different from object-oriented programming languages ​​such as C++ and Java .
Its compilers mainly include Clang , GCC , WIN-TC , SUBLIME , MSVC , Turbo C , etc.
2. The basic format of C language programming code.
        
#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

char               character data type
shortShort             _
int                 shaping
long               long integer
long long       longer shaping
float               single-precision floating point number ( 8 significant digits, representation range: -3.40E+38~3.40E+38 )
double           double-precision floating point number ( 16 significant digits, representation range: -1.79E+308~-1.79E+308 )
Note: Each type of space has a different size
Space size for various data types:
#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

Constant: An unchanging value, which is represented by the concept of constant in C language . Some values ​​in life are unchanging (such as: pi, gender, ID number, blood type, etc.).
Variable: variable value, represented by variables in C language (for example: age, weight, salary).
         4.1 How to define 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.4 Scope and life cycle of variables
        1. Scope : It is a programming concept. Generally speaking, the names used in a piece of program code are not always valid.
, and the scope of code that limits the availability of this name is the scope of this name.
                1. The scope of a local variable is the local scope where the variable is located.
                2. The scope of global variables is the entire project.
        2. Life cycle : The life cycle of a variable refers to the period of time between the creation of the variable and the destruction of the variable.
                1. The life cycle of local variables is: the life cycle begins when entering the scope and ends when it exits the scope.
                2. The life cycle of global variables is: the life cycle of the entire program.

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

        5.1 String: This string of characters enclosed by double quotes is called a string literal ( String Literal), or simply a string. For example, "Just do it!\n" in the first code
#include <stdio.h>
int main()
{
    printf("Hello\n");
    printf("Just do it!\n");
    return 0; 
}
        5.2 Escape character: An escape character is a character starting with "\", followed by one or several characters. Its meaning is to convert the character after the backslash "\" into another meaning.
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;
}
Print the result:
        4. Escape character \t: horizontal tab character, the output result is equivalent to the distance opened by pressing the Tab key once
#include<stdio.h>
int main()
{
	printf("a\ta");
	return 0;
}

Output result:

              The distance between the two letters a is the distance of one tab opened by \t
        5. Escape characters \ddd and \xdd: ddd represents 1 to 3 octal numbers. Such as: \130,
                                        
                                                dd represents 2 hexadecimal digits. Such as: \x30
                                               What is output when printing is that after the corresponding expressed base is converted into decimal, the decimal corresponds to the characters corresponding to the ASCII code table.
#include<stdio.h>
int main()
{
	printf("\101\n");
	printf("\x42");
	return 0;
}

Output result:

        Among them, the number represented by octal \x42 converted into decimal is 65, and the number represented by hexadecimal \x42 converted into decimal is 66.

          6. Escape character \\: used to represent a backslash to prevent it from being interpreted as an escape sequence character, which is equivalent to canceling the character that has been escaped with \, just like a double negative has a positive effect. And \\ also has one of the most commonly used uses in codes, which is used to explain the meaning of the code, facilitate understanding of the function of the corresponding code, and facilitate others to read.
#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.

                        2. Some codes in the code are difficult to understand. You can add comments.
        Comments come in two styles:
                        C language style comments /*xxxxxx*/
                        Defect: cannot nest comments
                        C++ style comments //xxxxxxxx
                        You can comment one line or multiple lines

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

        If you study hard, you can find a good job
        If you don’t study, you can’t find a good job
        This is the choice!
For example, use an if statement to implement:
#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:

        1. We know that when we learn C language programming, we always want to know the result after writing a code, and want to print the result on our screen. At this time, we will frequently use a function: printing information to the screen in a certain format (printf ).
        2. During the programming process, we will frequently copy strings ( strcpy ).
        3. In programming, we also calculate, and we always calculate operations such as n raised to the kth power ( pow ).
        If you want to know more about more library functions in C language, you can go to the C++ official website to view:
        C++ official website (English version): cppreference.com
         C++ official website (Chinese version): cppreference.com
A simple classification of library functions:
                                        1. IO function
                                        2. String operation functions
                                        3.Character operation function
                                        4. Memory operation function
                                        5. Time/date function
                                        6. Mathematical functions
                                        7. Other library functions
Note : But one secret you must know about library functions is: when using library functions, you must include the header file corresponding to #include .

        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个元素
         9.2 Subscript of array: C language stipulates that each element of the array has a subscript, and the subscript starts from 0 .
Arrays can be accessed through subscripts.
                
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: = +=         -=         *=         /=         &=         ^ =          |=            >>=   <<=                

        The assignment operator is a great operator that allows you to get a value that you were not happy with before. In other words, you can reassign yourself.
        10.5 Unary 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.

        10.6 Relational operators:
> more than the
>= greater or equal to
< less than
<= less than or equal to
!= Used to test "inequality"
== Used to test "equality"

        10.7 Logical operators:
&& logical AND
|| logical or

        10.8 Conditional operators: exp1 ? exp2 : exp3
        10.9 Comma expressions: exp1 , exp2 , exp3,...expN
        10.10. Subscripted references, function calls and structure members:         [] () .          ->

11. Common keywords: C language provides a wealth of keywords. These keywords are preset by the language itself. Users cannot create keywords themselves.

auto           break            case           char           const            continue           default           do          ​ double         else           enum           extern         float           for            goto           if            int            long           register             return            short           signed                 sizeof           static         struct   switch           typedef        union           unsigned           void           volatile           while
十二、#define 定义常量和宏
        12.1 #define 定义常量
#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的地址。注:这里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;
}

打印结果:

        定义一个整型的变量a=10,用&a取出变量a的地址并放入指针变量p中,指针变量p的类型(也就是a的类型)是整型,用解引用符找到p变量的指向对象(a),并对指向对象重新赋值20,打印a的结果时发现打印的就是第二次赋值的20。
        13.2 指针变量的大小,用到前面所介绍的sizeof
#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个字节。

14. Structure: Structure is a particularly important knowledge point in C language. Structure enables C language to describe complex types.
For example, describing a student, the student contains several pieces of information: name + age + gender + student number . This can only be described using structures, specifically combining single types together.
#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 "->".

Guess you like

Origin blog.csdn.net/m0_64616721/article/details/124147903