Cprogramming 简明教程
C Language - Cheat Sheet
本 C 语言备忘单从基础到高级水平快速概述了 C 语言概念。此备忘单非常适用于学生、开发人员和准备面试的人员。浏览本备忘单了解 C programming language. 的所有基本和高级概念
This C language cheat sheet gives a quick overview of C language concepts starting from the basics to the advanced level. This cheat sheet is very useful for students, developers, and those who are preparing for an interview. Go through this cheat sheet to learn all basic and advanced concepts of C programming language.
Basis Structure of C Program
basic structure of a C program 让您了解在 C 语言中编写程序所需使用的基本语句。以下是 C 程序的基本结构 -
The basic structure of a C program gives you an idea about the basic statements that you need to use to write a program in C language. The following is the basic structure of a C program −
// Preprocessor directive/header file inclusion section
#include <stdio.h>
// Global declaration section
// the main() function
int main() {
// Variable declarations section
int x, y;
// other code statements section
// Return o
return 0;
}
// Other user-defined function definition section
#include 是在 C 程序中包含头文件的预处理器指令。 stdio.h 是定义所有输入和输出相关函数的头文件。
#include is a preprocessor directive that includes the header file in the C program. The stdio.h is a header file where all input and output-related functions are defined.
= main() 函数[id="_main_function"]==== main() 函数
==== main() Function
main() function 是 C 程序的入口点,程序的执行从 main() 函数开始。
The main() function is an entry point of a C program, the program’s executions start from the main() function.
以下是 main() 函数的语法 -
The below is the syntax of the main() function −
int main() {
return 0;
}
= 注释[id="_comments"]=== 注释
=== Comments
有两种类型的 comments in C language. 单行注释和多行注释。注释被编译器忽略。
There are two types of comments in C language. Single-line and multi-line comments. Comments are ignored by the compilers.
= 单行注释[id="_single_line_comments"]==== 单行注释
==== Single-line Comments
使用 // 撰写单行注释。
Use // to write a single-line comment.
// This is a single-line comment
= 多行注释[id="_multi_line_comments"]==== 多行注释
==== Multi-line Comments
在文本前后使用 /* 和 */ 在 C 语言中编写多行注释。
Use /* and */ before and after the text to write multi-line comments in C language.
/*
This is line 1
This is line 2
..
*/
= 打印 (printf() 函数)[id="_printing_printf_function"]=== 打印 (printf() 函数)
=== Printing (printf() Function)
printf() 函数是库函数,用于在控制台输出上打印格式化的文本。当您需要打印任何内容时,请使用 printf()。
The printf() function is a library function to print the formatted text on the console output. Whenever you want to print anything, use the printf().
= 示例[id="_example"]====示例
==== Example
printf("Hello world");
= 用户输入 (scanf() 函数)[id="_user_input_scanf_function"]=== 用户输入 (scanf() 函数)
=== User Input (scanf() Function)
scanf() 函数用于从用户获取各种类型的输入。
The scanf() function is used to take various types of inputs from the user.
下面是 scanf() 函数的语法:
Here is the syntax of the scanf() function −
scanf("format_specifier", &variable_name);
= 格式说明符[id="_format_specifiers"]==== 格式说明符
==== Format Specifiers
以下是 printf() 和 scanf() 函数中使用的 C 格式说明符,用于打印/输入特定类型的值。
The following is the list of C format specifiers that are used in printf() and scanf() functions to print/input specific type of values.
Format Specifier |
Type |
%c |
Character |
%d |
Signed integer |
%e or %E |
Scientific notation of floats |
%f |
Float values |
%g or %G |
Similar as %e or %E |
%hi |
Signed integer (short) |
%hu |
Unsigned Integer (short) |
%i |
Unsigned integer |
%l or %ld or %li |
Long |
%lf |
Double |
%Lf |
Long double |
%lu |
Unsigned int or unsigned long |
%lli or %lld |
Long long |
%llu |
Unsigned long long |
%o |
Octal representation |
%p |
Pointer |
%s |
String |
%u |
Unsigned int |
%x or %X |
Hexadecimal representation |
= 示例[id="_example"]====示例
==== Example
#include <stdio.h>
int main(){
int age = 18;
float percent = 67.75;
printf("Age: %d \nPercent: %f", age, percent);
return 0;
}
Age: 18
Percent: 67.750000
= 数据类型[id="_data_types"]=== 数据类型
=== Data Types
data types 指定存储在变量中的数据类型和大小。数据类型分为 3 个部分:
The data types specify the type and size of the data to be stored in a variable. Data types are categorized in 3 sections −
-
Basic Data Types
-
Derived Data Types
-
User-defined Data Types
= 基本数据类型[id="_basic_data_types"]==== 基本数据类型
==== Basic Data Types
基本数据类型是 C 语言中的内置数据类型,也可以用于创建派生数据类型。
The basic data types are the built-in data types in C language and they are also used to create derived data types.
Data Type |
Name |
Description |
int |
Integer |
Represents integer Value |
char |
Character |
Represents a single character |
float |
Float |
Represents float value |
= 派生数据类型[id="_derived_data_types"]==== 派生数据类型
==== Derived Data Types
派生数据类型是从基本数据类型派生的。派生数据类型包括:
The derived data types are derived from the basic data types. The derived data types are −
-
Array
-
Pointer
= 用户定义数据类型[id="_user_defined_data_types"]==== 用户定义数据类型
==== User-defined Data Types
用户定义数据类型由程序员创建,用于处理不同类型的数据,并基于需求。用户定义数据类型包括:
The user-defined data types are created by the programmer to handle data of different type and based on the requirements. The user-defined data types are −
-
Structures
-
Unions
-
Enumerations
= 基本输入和输出[id="_basic_input_output"]=== 基本输入和输出
=== Basic Input & Output
对于 basic input and output in C language ,我们使用 printf() 和 scanf() 函数。
For basic input and output in C language, we use printf() and scanf() functions.
printf() 函数用于在控制台上打印格式化文本。
The printf() function is used to print the formatted text on the console.
printf("Hello world");
scanf() 函数用于接收用户的输入。
The scanf() function is used to take input from the user.
scanf("%d", &x); // Integer input
scanf("%f", &y); // float input
scanf("%c", &z); // Character Input
scanf("%s", name); // String input
= 基本输入和输出示例[id="_example_of_basic_input_and_output"]==== 基本输入和输出示例
==== Example of Basic Input and Output
#include <stdio.h>
int main() {
int num;
printf("Input any integer number: ");
scanf("%d", &num);
printf("The input is: %d\n", num);
return 0;
}
Input any integer number: The input is: 0
= 标识符[id="_identifiers"]=== 标识符
=== Identifiers
C identifiers 是变量、常量、函数等的用户定义名称。以下是定义标识符的规则:
C identifiers are user-defined names for variables, constants, functions, etc. The following are the rules for defining identifiers −
-
Keywords can’t be used as identifiers.
-
Only alphabets, underscore symbol (_), and digits are allowed in the identifier.
-
The identifier must start either with an alphabet or an underscore.
-
The same identifier can’t be used as the name of two entities.
-
Identifiers should be meaningful and descriptive.
示例——有效标识符[id="_examples_of_valid_identifiers"]==== 示例——有效标识符
==== Examples of Valid Identifiers
age, _name, person1, roll_no
关键字[id="_keywords"]=== 关键字
=== Keywords
C keywords 是 C 编译器中使用用于特定目的的反向字,不能用作标识符。
C keywords are the reversed words in the C compiler, which are used for specific purposes and must not be used as an identifier.
以下是 C 语言中的关键字:
The following are the keywords in C language −
auto |
double |
int |
struct |
break |
else |
long |
switch |
case |
enum |
register |
typedef |
char |
extern |
return |
union |
continue |
for |
signed |
void |
do |
if |
static |
while |
default |
goto |
sizeof |
volatile |
const |
float |
short |
unsigned |
变量[id="_variables"]=== 变量
=== Variables
C variables 是程序可用于访问和操作数据的存储区域的名称。
C variables are the name given to a storage area that our programs can use to access and manipulate the data.
声明变量的语法[id="_syntax_of_declaring_a_variable"]==== 声明变量的语法
==== Syntax of Declaring a Variable
data_type variable_name;
转义序列[id="_escape_sequences"]=== 转义序列
=== Escape Sequences
Escape sequences 是以转义字符(反斜杠 \)为结尾的特殊字符。转义序列有特殊含义,用于打印无法正常打印的字符。
Escape sequences are the special characters followed by the escape (backward slash \). Escape sequences have special meanings and are used for printing those characters that cannot be printed normally.
以下是 C 语言中的转义序列列表:
Here is the list of escape sequences in C language −
Escape sequence |
Meaning |
|\ character |
\' |
' character |
\" |
" character |
\? |
? character |
\a |
Alert or bell |
\b |
Backspace |
\f |
Form feed |
\n |
Newline |
\r |
Carriage return |
\t |
Horizontal tab |
\v |
Vertical tab |
\ooo |
Octal number of one to three digits |
\xhh . . . |
运算符[id="_operators"]=== 运算符
=== Operators
Operators 是用于执行特定数学或逻辑运算的特殊符号。
Operators are the special symbols that are used to perform specific mathematical or logical operations.
以下是 C 语言中使用的运算符:
Below are the operators used in C language −
Operators |
Symbols |
Description |
=, +=, -=, <⇐ |
Performs assignment operations i.e., assigning values to variables. |
|
+, -, *, /, % |
Performs arithmetic operations. |
|
<, >, ⇐, >=, ==, != |
Performs comparisons on two operands. |
|
&&, |
||
, ! |
Performs logical operations such as logical AND, OR, and NOT. |
|
&, ^, |
, <<, >>, ~ |
Performs bitwise operations. |
? : |
Performs conditional operation for decision-making. |
|
, sizeof, &, *, ⇒, . |
Used for performing various other operations. |
= 运算符示例[id="_example_of_operators"]==== 运算符示例
==== Example of Operators
result = num1 + num2;
if(result >=10){
printf("Greater than 10.");
}
= 条件语句[id="_conditional_statements"]=== 条件语句
=== Conditional Statements
C 语言提供了以下条件语句−
C language provides the following conditional statements −
-
if Statement
-
if-else Statement
-
if-else-if Statement
-
Nested if-else Statement
-
Switch Statement
-
Ternary Operator
= if 语句[id="_if_statement"]==== if 语句
==== if Statement
if statement 由一个布尔表达式后跟一个或多个语句组成。
An if statement consists of a Boolean expression followed by one or more statements.
if 语句的语法为 −
The syntax of if statement is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
= if-else 语句[id="_if_else_statement"]==== if-else 语句
==== if-else statement
if-else statement 后跟一个可选的 else 语句,当布尔表达式为 false 时执行该语句。
An if-else statement can be followed by an optional else statement, which executes when the Boolean expression is false.
if 语句的语法为 −
The syntax of the if statement is −
if (Boolean expr){
Expression;
. . .
}
else{
Expression;
. . .
}
= if-else-if 语句[id="_if_else_if_statement"]==== if-else-if 语句
==== if-else-if Statement
if-else-if 语句也称为 ladder if-else。它用于在条件不成立时检查多个条件。
The if-else-if statement is also known as the ladder if-else. It is used to check multiple conditions when a condition is not true.
if-else-if 语句的语法 −
The syntax of if-else-if statement −
if(condition1){
}
else if(condition2){
}
…
else{
}
= 嵌套 if 语句[id="_nested_if_statements"]==== 嵌套 if 语句
==== Nested if Statements
使用 nested if statements ,可在另一个 if 或 else-if 语句中使用一个 if 或 else-if 语句。
By using the nested if statements, you can use one if or else-if statement inside another if or else-if statement(s).
嵌套 if 语句的语法 −
The syntax of nested if statements −
if (expr1){
if (expr2){
block to be executed when
expr1 and expr2 are true
}
else{
block to be executed when
expr1 is true but expr2 is false
}
}
= Switch 语句[id="_switch_statement"]==== Switch 语句
==== Switch Statement
switch statement 允许将一个变量与值列表进行相等性测试。
A switch statement allows a variable to be tested for equality against a list of values.
switch 语句的语法 −
The syntax of the switch statement is −
switch (Expression){
// if expr equals Value1
case Value1:
Statement1;
Statement2;
break;
// if expr equals Value2
case Value2:
Statement1;
Statement2;
break;
.
.
// if expr is other than the specific values above
default:
Statement1;
Statement2;
}
= 三元运算符[id="_ternary_operator"]==== 三元运算符
==== Ternary Operator
ternary operator (?:) 也被称为条件运算符。可用作 if-else 语句的替换。
The ternary operator (?:) is also known as the conditional operator. It can be used as a replacement for an if-else statement.
三元运算符的语法 −
The syntax of the ternary operator is −
(condition) ? true_block: false_block;
= 循环[id="_loops"]=== 循环
=== Loops
C loops 用于分别执行一个或多个语句块指定的次数或者直到满足某个条件为止。以下是 C 语言中的循环语句 −
C loops are used to execute blocks of one or more statements respectively a specified number of times, or till a certain condition is reached. The following are the loop statements in C language −
-
while Loop
-
do…while Loop
-
for Loop
= while 循环[id="_while_loop"]==== while 循环
==== while Loop
while loop 是一个入口控制循环,在执行循环主体之前检查条件。
The while loop is an entry-control loop where the condition is checked before executing the loop body.
while 循环的语法 −
The syntax of the while loop is −
while(test_condition){
// Statement(s);
}
= do…while 循环[id="_dowhile_loop"]==== do…while 循环
==== do…while Loop
do…while 循环是一个出口控制循环,在这种循环中,循环体在检查条件之前执行。
The do…while loop is an exit control loop where the body of the loop executes before checking the condition.
do…while 循环的语法 −
The syntax of do…while loop is −
do{
// Statement(s);
}while(test_condition);
= for 循环[id="_for_loop"]==== for 循环
==== for Loop
for 循环也是一个入口控制循环,其中,元素(初始化、测试条件和增量)被组合在一起,以在有 for 关键字的括号内形成一个 for 循环。
The for loop is also an entry-controlled loop where the elements (initialization, test condition, and increment) are placed together to form a for loop inside the parenthesis with the for keyword.
for 循环的语法 −
The syntax of the for loop is −
for(initialization ; test condition ; increment){
// Statement (s);
}
= 跳转语句 [id="_jump_statements"] === 跳转语句
=== Jump Statements
跳转语句用于将程序流程从一处传输到另一处。以下是C语言中的跳转语句 -
Jump statements are used to transfer the flow of the program from one place to another. The following are the jump statements in C language −
-
goto Statement
-
break Statement
-
continue Statement
= goto 语句 [id="_goto_statement"] ==== goto 语句
==== goto Statement
goto statement 将程序的控制权传输到特定的标签。你需定义一个标签,后跟冒号 (:)。goto 语句可以向上或向下传输程序的流程。
The goto statement transfers the program’s control to a specific label. You need to define a label followed by the colon (:). The goto statement can transfer the program’s flow up or down.
goto 语句的语法是 -
The syntax of the goto statement is −
label_name:
label_name:
//Statement(s)
if(test_condition){
goto label_name;
}
= break 语句 [id="_break_statement"] ==== break 语句
==== break Statement
break statement 可用于循环和 switch 语句。break 语句终止循环执行,并将程序的控制权传输到循环体外部。
The break statement can be used with loops and switch statements. The break statement terminates the loop execution and transfers the program’s control outside of the loop body.
break 语句的语法是 -
The syntax of the break statement is −
while(condition1){
. . .
. . .
if(condition2)
break;
. . .
. . .
}
= continue 语句 [id="_continue_statement"] ==== continue 语句
==== continue Statement
continue statement 用于跳过在当前迭代中循环内其余语句的执行,并将其传至下一循环迭代。
The continue statement is used to skip the execution of the rest of the statement within the loop in the current iteration and transfer it to the next loop iteration.
continue 语句的句法是 -
The syntax of the continue statement is −
while (expr){
. . .
. . .
if (condition)
continue;
. . .
}
= 用户定义函数 [id="_user_defined_functions"] === 用户定义函数
=== User-defined Functions
user-defined function 由用户定义,以执行特定任务以实现代码可重用性和模块化。
The user-defined function is defined by the user to perform specific tasks to achieve the code reusability and modularity.
= 用户定义函数示例 [id="_example_of_user_defined_function"] ==== 用户定义函数示例
==== Example of user-defined function
#include <stdio.h>
// Function declaration
int add(int, int);
// Function definition
int add(int a, int b) { return (a + b); }
int main() {
int num1 = 10, num2 = 10;
int res_add;
// Calling the function
res_add = add(num1, num2);
// Printing the results
printf("Addition is : %d\n", res_add);
return 0;
}
Addition is : 20
= 数组 [id="_arrays"] === 数组
=== Arrays
数组是存储在连续内存位置中、具有相似数据类型的的数据项集合。数据项可以是原数据类型(int、float、char),或用户定义类型,例如结构或指针可以存储在数组中。
An array is a collection of data items of similar data type which are stored at a contiguous memory location. The data item may be primary data types (int, float, char), or user-defined types such as struct or pointers can be stored in an array.
C Arrays 可以分为两种类型 -
C Arrays can be of two types −
-
One-dimensional (1D) Array − A one-dimensional array is a single list of data items of the same data type.
-
Multi-dimensional Arrays − A multi-dimensional array such as a two-dimensional array is an array of arrays.
= 数组语法 [id="_syntax_of_arrays"]==== 数组语法
==== Syntax of Arrays
下面是不同类型的数组声明的语法 -
The following is the syntax of declarations of different types of arrays −
type array_name [size1]; // One-dimensional array
type array_name [size1][size2]; // Two-dimensional arrays
type array_name [size1][size2][size3]; // Three-dimensional arrays
= 一维数组示例 [id="_example_of_one_dimensional_array"]==== 一维数组示例
==== Example of One-dimensional Array
#include <stdio.h>
int main(){
int numbers[5] = {10, 20, 30, 40, 50};
int i; // loop counter
// Printing array elements
printf("The array elements are : ");
for (i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
The array elements are : 10 20 30 40 50
= 二维数组示例 [id="_example_of_two_dimensional_arrays"]==== 二维数组示例
==== Example of Two-dimensional Arrays
#include <stdio.h>
int main () {
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}
a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8
= 字符串 [id="_strings"]=== 字符串
=== Strings
C string 是一个字符序列,即 char 数据类型的数组,它以用 '\0' 表示的“空字符”结尾。要使用 scanf() 和 printf() 函数来读取和打印字符串,您需要使用 "%s" 格式说明符。
C string is a sequence of characters i.e., an array of char data type, terminated by "null character" represented by '\0'. To read and print the string using scanf() and printf() functions, you will have to use the "%s" format specifier.
String Declaration
String Declaration
char string_name[size];
Reading String
Reading String
scanf("%s", string_name);
Printing String
Printing String
printf("%s", string_name);
= C 字符串示例 [id="_example_of_c_strings"]==== C 字符串示例
==== Example of C strings
#include <stdio.h>
int main() {
char name[20];
printf("Enter a name: ");
scanf("%s", name);
printf("You entered: %s", name);
return 0;
}
= 字符串函数 [id="_strings_functions"]==== 字符串函数
==== Strings Functions
C 标准库 string.h 提供了各种函数来处理字符串。下面是 C 字符串函数列表 -
C standard library string.h provides various functions to work with the strings. Here is the list of C string functions −
Sr.No. |
Function |
Description |
1 |
Appends the string pointed to, by src to the end of the string pointed to by dest. |
|
2 |
Appends the string pointed to, by src to the end of the string pointed to, by dest up to n characters long. |
|
3 |
Searches for the first occurrence of the character c (an unsigned char) in the string pointed to, by the argument str. |
|
4 |
Compares the string pointed to, by str1 to the string pointed to by str2. |
|
5 |
Compares at most the first n bytes of str1 and str2. |
|
6 |
Compares string str1 to str2. The result is dependent on the LC_COLLATE setting of the location. |
|
7 |
Copies the string pointed to, by src to dest. |
|
8 |
Copies up to n characters from the string pointed to, by src to dest. |
|
9 |
Calculates the length of the initial segment of str1 which consists entirely of characters not in str2. |
|
10 |
Searches an internal array for the error number errnum and returns a pointer to an error message string. |
|
11 |
Computes the length of the string str up to but not including the terminating null character. |
|
12 |
Finds the first character in the string str1 that matches any character specified in str2. |
|
13 |
Searches for the last occurrence of the character c (an unsigned char) in the string pointed to by the argument str. |
|
14 |
Calculates the length of the initial segment of str1 which consists entirely of characters in str2. |
|
15 |
Finds the first occurrence of the entire string needle (not including the terminating null character) which appears in the string haystack. |
|
16 |
Breaks string str into a series of tokens separated by delim. |
|
17 |
Transforms the first n characters of the string src into current locale and places them in the string dest. |
= 结构[id="_structures"]=== 结构
=== Structures
C structures 是不同类型的数据的集合。结构被认为是用户自定义的类型,您可以用它们来对不同类型的数据项进行分组。
C structures are the collection of different data types. Structures are considered user-defined data types where you can group data items of different data types.
= 结构声明语法[id="_structure_declaration_syntax"]==== 结构声明语法
==== Structure Declaration Syntax
struct struct_name {
type1 item1;
type2 item2;
.
.
}structure_variable;
= 结构示例[id="_example_of_structure"]==== 结构示例
==== Example of Structure
#include <stdio.h>
struct book{
char title[10];
char author[20];
double price;
int pages;
};
int main(){
struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325};
printf("Title: %s \n", book1.title);
printf("Author: %s \n", book1.author);
printf("Price: %lf\n", book1.price);
printf("Pages: %d \n", book1.pages);
printf("Size of book struct: %d", sizeof(struct book));
return 0;
}
Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Size of book struct: 48
= 联合[id="_unions"]=== 联合
=== Unions
C union 是一个用户自定义的类型,允许在相同内存位置处存储不同类型的数据项集合。
C union is a user-defined data type that allows to store set of data items of different data types in the same memory location.
= 联合声明语法[id="_syntax_of_union_declaration"]==== 联合声明语法
==== Syntax of Union Declaration
union [union tag]{
member definition;
member definition;
...
member definition;
} [one or more union variables];
= 联合示例[id="_example_of_union"]==== 联合示例
==== Example of Union
#include <stdio.h>
union Data{
int i;
float f;
};
int main(){
union Data data;
data.i = 10;
data.f = 220.5;
printf("data.i: %d \n", data.i);
printf("data.f: %f \n", data.f);
return 0;
}
data.i: 1130135552
data.f: 220.500000
= 枚举 (enum)[id="_enumerations_enums"]=== 枚举 (enum)
=== Enumerations (enums)
C enumeration (enum) 是一个枚举数据类型,其包含一组整数常量。
C enumeration (enum) is an enumerated data type that consists of a group of integral constants.
= 枚举声明的语法[id="_syntax_of_enum_declaration"]==== 枚举声明的语法
==== Syntax of enum Declaration
enum myenum {val1, val2, val3, val4};
= 枚举 (enum) 示例[id="_example_of_enumeration_enum"]==== 枚举 (enum) 示例
==== Example of Enumeration (enum)
#include <stdio.h>
enum status_codes { OKAY = 1, CANCEL = 0, ALERT = 2 };
int main() {
// Printing values
printf("OKAY = %d\n", OKAY);
printf("CANCEL = %d\n", CANCEL);
printf("ALERT = %d\n", ALERT);
return 0;
}
OKAY = 1
CANCEL = 0
ALERT = 2
= 指针[id="_pointers"]=== 指针
=== Pointers
C pointers 是派生数据类型,其用于存储另一个变量的地址,并且还可以用于通过该位置访问和控制存储有变量数据的内存。
C pointers are derived data types that are used to store the address of another variable and can also be used to access and manipulate the variable’s data stored at that location.
= 指针声明的语法[id="_syntax_of_pointer_declaration"]==== 指针声明的语法
==== Syntax of Pointer Declaration
data_type *pointer_name;
= 指针初始化的语法[id="_syntax_of_pointer_initialization"]==== 指针初始化的语法
==== Syntax of Pointer Initialization
如果声明了一个指针,则可以使用以下语法来用另一个变量的地址初始化一个指针 −
If you are declared a pointer, below is the syntax to initialize a pointer with the address of another variable −
pointer_name = &variable_name;
= 指针示例[id="_pointer_example"]==== 指针示例
==== Pointer Example
#include <stdio.h>
int main() {
int x = 10;
// Pointer declaration and initialization
int * ptr = & x;
// Printing the current value
printf("Value of x = %d\n", * ptr);
// Changing the value
* ptr = 20;
// Printing the updated value
printf("Value of x = %d\n", * ptr);
return 0;
}
Value of x = 10
Value of x = 20
= 指针类型[id="_type_of_pointers"]==== 指针类型
==== Type of Pointers
C 语言中具有多种类型的指针。它们是 −
There are various types of pointers in C language. They are −
-
Wild pointer
-
Complex pointers
-
File pointers
-
Double pointers
= 动态内存分配[id="_dynamic_memory_allocations"]=== 动态内存分配
=== Dynamic Memory Allocations
变量的内存会在编译时进行声明。C 语言提供了一些函数用于动态内存分配,这些函数使得可以在运行时为变量分配内存。
Memories for variables are declared at compile-time. C language provides some functions for dynamic memory allocations that allow to allocation of memory for the variables at run time.
动态内存分配的函数有 −
The functions for dynamic memory allocation are −
-
malloc()
-
calloc()
-
realloc()
-
free()
= malloc() 函数[id="_malloc_function"]==== malloc() 函数
==== malloc() Function
malloc() function 分配请求的内存(指定大小的一定数量的块),并返回对其的指针。
The malloc() function allocates the requested memory (number of blocks of the specified size) and returns a pointer to it.
malloc() 函数的语法为 −
The syntax of malloc() function is −
malloc (size_t size);
calloc() Function
= calloc() 函数[id="_calloc_function"]==== calloc() 函数
==== calloc() Function
calloc() function 分配所请求的内存(指定大小的区块数),并返回 void 指针。calloc() 函数将分配的内存设置为零。
The calloc() function allocates the requested memory (number of blocks of the specified size) and returns the void pointer. The calloc() function sets allocated memory to zero.
calloc() 函数的语法为:-
The syntax of calloc() function is −
void *calloc(size_t nitems, size_t size)
= realloc() 函数[id="_realloc_function"]==== realloc() 函数
==== realloc() Function
realloc() function 尝试调整以前通过调用 malloc() 或 calloc() 函数分配的指针指向的内存区块的大小。
The realloc() function attempts to resize the memory block pointed to by a pointer that was previously allocated with a call to malloc() or calloc() function.
realloc() 函数的语法为:-
The syntax of realloc() function is −
void *calloc(size_t nitems, size_t size)
= free() 函数[id="_free_function"]==== free() 函数
==== free() Function
free() function 释放以前通过调用 calloc()、malloc() 或 realloc() 分配的内存。
The free() function deallocates the memory previously allocated by a call to calloc(), malloc(), or realloc().
realloc() 函数的语法为:-
The syntax of realloc() function is −
void *calloc(size_t nitems, size_t size)
= 文件处理[id="_file_handling"]==== 文件处理
=== File Handling
File handling 指执行文件上的各种操作,例如创建、写入、读取、删除、移动、重命名文件等。C 语言提供各种文件处理函数。
File handling refers to perform various operations on files such as creating, writing, reading, deleting, moving, renaming files, etc. C language provides various functions for file handling.
= 文件操作[id="_file_operations"]==== 文件操作
==== File Operations
以下是使用 C 语言文件处理函数可执行的文件操作:
The following are the operations that can perform a file using C language file handling functions −
-
Creating a new file
-
Opening an existing file
-
Writing data to a file
-
Appending data to a file
-
Reading data from a file
-
Renaming a file
-
Deleting a file
-
Closing a file
= 文件处理函数[id="_file_handling_functions"]==== 文件处理函数
==== File Handling Functions
以下是在 C 中列出的文件处理函数:-
Following is the list of file handling functions in C −
Function |
Description |
Creates, and opens a file in various modes. |
|
Closes a file. |
|
Writes data to a file. |
|
Reads data from a file. |
|
Write and read data to/from a binary file. |
|
Renames a file. |
|
Deleted a file. |
= 文件处理示例[id="_example_of_file_handling"]==== 文件处理示例
==== Example of File Handling
以下为 C 语言中文件处理的示例 -
Here is an example of file handling in C language −
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
char file_name[] = "my_file.txt";
char write_data[100] = "Tutorials Point";
char read_data[100];
// Opening file in write mode
file = fopen("file_name.txt", "w");
if (file == NULL) {
printf("Error\n");
return 1;
}
// Writing to the file
fprintf(file, "%s", write_data);
// Closing the file
fclose(file);
// Again, opening the file in read mode
file = fopen("file_name.txt", "r");
if (file == NULL) {
printf("Error.\n");
return 1;
}
// Reading data from the file
if (fgets(read_data, 100, file) != NULL) {
// Printing it on the screen
printf("File's data:\n%s\n", read_data);
}
fclose(file);
return 0;
}
File's data:
Tutorials Point
= 预处理指令[id="_preprocessor_directives"]=== 预处理指令
=== Preprocessor Directives
preprocessor directives 是预编译的一部分,并以井号 (#) 字符开头。这些指令指示编译器在开始编译过程之前展开 include 并展开代码。
The preprocessor directives are part of pre-compilation and start with the hash (#) character. These directives instruct the compiler to expand include and expand the code before starting the process of compilation.
以下是预处理指令列表 -
Here is the list of preprocessor directives −
Directive |
Description |
# define |
Substitutes a preprocessor macro. |
#include |
Inserts a particular header from another file. |
#undef |
Undefines a preprocessor macro. |
#ifdef |
Returns true if this macro is defined. |
#ifndef |
Returns true if this macro is not defined. |
#if |
Tests if a compile time condition is true. |
#else |
The alternative for #if. |
#elif |
#else and #if in one statement. |
#endif |
Ends preprocessor conditional. |
#error |
Prints error message on stderr. |
#pragma |
Issues special commands to the compiler, using a standardized method. |
= 预处理指令示例[id="_example_of_preprocessor_directive"]==== 预处理指令示例
==== Example of Preprocessor Directive
这是 #define 的示例,它是 C 语言中预处理器指令之一 -
This is an example of #define which is one of the preprocessor directives in C language −
#define MAX_ARRAY_LENGTH 20
= 标准库 [id="_standard_libraries"]=== 标准库
=== Standard Libraries
以下是常用库(C 头文件)的列表 -
Here is the list of commonly used libraries (C header files) −
Header file |
Usage |
Provides functions for standard input and outputs. |
|
Provides functions for various string operations. |
|
Provides function for mathematical operations. |
|
Provides various utility functions for memory allocations, type conversions, etc. |
|
Provides date-time related functions. |