[关闭]
@zhongdao 2018-11-28T10:20:05.000000Z 字数 26976 阅读 1616

X分钟速成Y 其中 Y=C (中英对照版)

中英对照版

Ah, C. Still the language of modern high-performance computing.
C语言在今天仍然是高性能计算的主要选择。

C is the lowest-level language most programmers will ever use, but it more than makes up for it with raw speed. Just be aware of its manual memory management and C will take you as far as you need to go.
C大概是大多数程序员用到的最接近底层的语言了,C语言原生的速度就很高了,但是别忘了C的手动内存管理,它会让你将性能发挥到极致。

About compiler flags
关于编译器参数

By default, gcc and clang are pretty quiet about compilation warnings and errors, which can be very useful information. Explicitly using stricter compiler flags is recommended. Here are some recommended defaults:
缺省情况下,gcc 和 clang是没有编译的警告和错误信息,而这些含有很多信息。 所以推荐使用更严格的编译器参数。

-Wall -Wextra -Werror -O2 -std=c99 -pedantic

For information on what these flags do as well as other flags, consult the man page for your C compiler (e.g. man 1 gcc) or just search online.
为了了解参数的信息,可以查看man信息,或者在线搜索。

  1. // Single-line comments start with // - only available in C99 and later.
  2. // 单行注释以//开始。(仅适用于C99或更新的版本。)
  3. /*
  4. Multi-line comments look like this. They work in C89 as well.
  5. 多行注释是这个样子的。(C89也适用。)
  6. */
  7. /*
  8. Multi-line comments don't nest /* Be careful */ // comment ends on this line...
  9. 多行的注释不支持嵌套,所以注释在上一行结束。
  10. */ // ...not this one! 这一行不是结束。
  11. // Constants: #define <keyword>
  12. // 常量: #define 关键词
  13. // Constants are written in all-caps out of convention, not requirement
  14. // 常量约定全部是大写,但不是必须。
  15. #define DAYS_IN_YEAR 365
  16. // Enumeration constants are also ways to declare constants.
  17. // All statements must end with a semicolon
  18. // 以枚举的形式来定义常量,所有的声明以分号结束。
  19. enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
  20. // MON gets 2 automatically, TUE gets 3, etc.
  21. // MON 的值自动是2,TUE值是3,等等
  22. // Import headers with #include
  23. // 用#include来导入头文件
  24. #include <stdlib.h>
  25. #include <stdio.h>
  26. #include <string.h>
  27. // (File names between <angle brackets> are headers from the C standard library.)
  28. // For your own headers, use double quotes instead of angle brackets:
  29. // (尖括号中的文件名是C标准库中的头文件)
  30. // 自己的头文件,采用双引号来代替尖括号。
  31. //#include "my_header.h"
  32. // Declare function signatures in advance in a .h file, or at the top of
  33. // your .c file.
  34. // 在.h文件中提前声明函数(或称为签名),或者在.c文件的头部。
  35. void function_1();
  36. int function_2(void);
  37. // Must declare a 'function prototype' before main() when functions occur after
  38. // your main() function.
  39. // 如果函数出现在main()之后,那么必须在main()之前先声明一个函数原型
  40. int add_two_ints(int x1, int x2); // function prototype
  41. // although `int add_two_ints(int, int);` is also valid (no need to name the args),
  42. // it is recommended to name arguments in the prototype as well for easier inspection
  43. // 虽然不带参数名称的函数声明是合法的,但是推荐在原型中命名参数,方便检查。
  44. // Your program's entry point is a function called
  45. // main with an integer return type.
  46. // 程序的入口是一个返回值为整型的main函数
  47. int main(void) {
  48. // your program
  49. }
  50. // The command line arguments used to run your program are also passed to main
  51. // argc being the number of arguments - your program's name counts as 1
  52. // argv is an array of character arrays - containing the arguments themselves
  53. // argv[0] = name of your program, argv[1] = first argument, etc.
  54. // 命令行参数被传给main, argc是参数个数,程序本身名字计数为1。 argv是字符数组的数组,
  55. // argv[0] 是程序本身名字, argv[1] 是第一个参数。
  56. int main (int argc, char** argv)
  57. {
  58. // print output using printf, for "print formatted"
  59. // %d is an integer, \n is a newline
  60. // 用printf打印到标准输出,可以设定格式,%d 代表整数, \n 代表换行
  61. printf("%d\n", 0); // => Prints 0
  62. ///////////////////////////////////////
  63. // Types 类型
  64. ///////////////////////////////////////
  65. // All variables MUST be declared at the top of the current block scope
  66. // 在使用变量之前我们必须先声明它们。
  67. // we declare them dynamically along the code for the sake of the tutorial
  68. // (however, C99-compliant compilers allow declarations near the point where the value is used)
  69. // 为了本教程的目的,我们沿着代码动态声明。
  70. // (但是,符合C99的编译器允许在值使用的地方声明)
  71. // ints are usually 4 bytes 整数通常是4字节
  72. int x_int = 0;
  73. // shorts are usually 2 bytes 短整通常2字节
  74. short x_short = 0;
  75. // chars are guaranteed to be 1 byte 字符保证1字节
  76. char x_char = 0;
  77. char y_char = 'y'; // Char literals are quoted with '' 字符变量需单引号包住
  78. // longs are often 4 to 8 bytes; long longs are guaranteed to be at least 8 bytes
  79. // 长整型一般需要4个字节到8个字节;而long long型则需要至少8个字节
  80. long x_long = 0;
  81. long long x_long_long = 0;
  82. // floats are usually 32-bit floating point numbers 一般用32位表示浮点数字
  83. float x_float = 0.0f; // 'f' suffix here denotes floating point literal。后缀'f'表示浮点数
  84. // doubles are usually 64-bit floating-point numbers 一般使用64位表示的浮点数字
  85. double x_double = 0.0; // real numbers without any suffix are doubles
  86. // integer types may be unsigned (greater than or equal to zero) 整数类型也可以无符号表示。(大于或等于零)
  87. unsigned short ux_short;
  88. unsigned int ux_int;
  89. unsigned long long ux_long_long;
  90. // chars inside single quotes are integers in machine's character set. 单引号中的char类型是机器的字符集中的整数。
  91. '0'; // => 48 in the ASCII character set.
  92. 'A'; // => 65 in the ASCII character set.
  93. // sizeof(T) gives you the size of a variable with type T in bytes 提供类型为T的变量的大小
  94. // sizeof(obj) yields the size of the expression (variable, literal, etc.). 生成表达式的大小(变量,文字等)
  95. printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words)(在大多数4字节字的机器上)
  96. // If the argument of the `sizeof` operator is an expression, then its argument is not evaluated (except VLAs (see below)).
  97. //如果`sizeof`运算符的参数是一个表达式,那么它的参数不会被计算(除了VLA(见下文))。
  98. // The value it yields in this case is a compile-time constant.
  99. // 在这种情况下它产生的值是编译时常量。
  100. int a = 1;
  101. // size_t is an unsigned integer type of at least 2 bytes used to represent the size of an object.
  102. // size_t是一个至少2个字节的无符号整数类型,用于表示对象的大小。
  103. size_t size = sizeof(a++); // a++ is not evaluated
  104. printf("sizeof(a++) = %zu where a = %d\n", size, a);
  105. // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture)
  106. // Arrays must be initialized with a concrete size.
  107. // 必须使用具体大小初始化数组
  108. char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes 这个数组占20字节
  109. int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes 这个数组占80字节
  110. // (assuming 4-byte words) 假设4字节字
  111. // You can initialize an array to 0 thusly:
  112. // 你可以将数组初始化为0:
  113. char my_array[20] = {0};
  114. // Indexing an array is like other languages -- or,rather, other languages are like C
  115. // 索引数组和其他语言类似 -- 好吧,其实是其他的语言像C
  116. my_array[0]; // => 0
  117. // Arrays are mutable; it's just memory!
  118. // 数组是可变的,其实就是内存的映射!
  119. my_array[1] = 2;
  120. printf("%d\n", my_array[1]); // => 2
  121. // In C99 (and as an optional feature in C11), variable-length arrays (VLAs) can be declared as well. The size of such an array need not be a compile time constant:
  122. // 在C99 (C11中是可选特性),变长数组(VLA)也可以声明长度。其长度不用是编译期常量。
  123. printf("Enter the array size: "); // ask the user for an array size 询问用户数组长度
  124. int array_size;
  125. fscanf(stdin, "%d", &array_size);
  126. int var_length_array[array_size]; // declare the VLA 声明VLA
  127. printf("sizeof array = %zu\n", sizeof var_length_array);
  128. // Example:
  129. // > Enter the array size: 10
  130. // > sizeof array = 40
  131. // Strings are just arrays of chars terminated by a NULL (0x00) byte, represented in strings as the special character '\0'.
  132. // 字符串就是以 NUL (0x00) 这个字符结尾的字符数组, NUL可以用'\0'来表示.
  133. // (We don't have to include the NULL byte in string literals; the compiler inserts it at the end of the array for us.)
  134. // (在字符串字面量中我们不必输入这个字符,编译器会自动添加的)
  135. char a_string[20] = "This is a string";
  136. printf("%s\n", a_string); // %s formats a string
  137. printf("%d\n", a_string[16]); // => 0
  138. // i.e., byte #17 is 0 (as are 18, 19, and 20)
  139. // 例如,17字节是0,NUL, 而18,19,20也一样。
  140. // If we have characters between single quotes, that's a character literal.
  141. // It's of type `int`, and *not* `char` (for historical reasons).
  142. // 单引号间的字符是字符字面量
  143. // 它的类型是'int', 而不是'char'(由于历史原因)
  144. int cha = 'a'; // fine 合法
  145. char chb = 'a'; // fine too (implicit conversion from int to char) 同样合法 (隐式类型转换
  146. // Multi-dimensional arrays: 多维数组
  147. int multi_array[2][5] = {
  148. {1, 2, 3, 4, 5},
  149. {6, 7, 8, 9, 0}
  150. };
  151. // access elements: 获取元素
  152. int array_int = multi_array[0][2]; // => 3
  153. ///////////////////////////////////////
  154. // Operators 操作符
  155. ///////////////////////////////////////
  156. // Shorthands for multiple declarations: 多个变量声明的简写
  157. int i1 = 1, i2 = 2;
  158. float f1 = 1.0, f2 = 2.0;
  159. int b, c;
  160. b = c = 0;
  161. // Arithmetic is straightforward 算数运算直截了当
  162. i1 + i2; // => 3
  163. i2 - i1; // => 1
  164. i2 * i1; // => 2
  165. i1 / i2; // => 0 (0.5, but truncated towards 0) (0.5,但会被化整为 0)
  166. // You need to cast at least one integer to float to get a floating-point result
  167. // 你需要把整型转换成浮点来得到一个浮点结果。
  168. (float)i1 / i2; // => 0.5f
  169. i1 / (double)i2; // => 0.5 // Same with double
  170. f1 / f2; // => 0.5, plus or minus epsilon 也许会有很小的误差
  171. // Floating-point numbers and calculations are not exact
  172. // 浮点数和浮点数运算都是近似值
  173. // Modulo is there as well 取模运算
  174. 11 % 3; // => 2
  175. // Comparison operators are probably familiar, but there is no Boolean type in C. We use ints instead.
  176. // 比较操作符可能很熟悉,但是C中没有布尔类型,用整型代替。
  177. // (Or _Bool or bool in C99.) 0 is false, anything else is true. (The comparison operators always yield 0 or 1.)
  178. // ( C99中有布尔) 0为假,其他均为真(比较操作符的返回值总是返回0或1)
  179. 3 == 2; // => 0 (false)
  180. 3 != 2; // => 1 (true)
  181. 3 > 2; // => 1
  182. 3 < 2; // => 0
  183. 2 <= 2; // => 1
  184. 2 >= 2; // => 1
  185. // C is not Python - comparisons don't chain.
  186. // C不是python, 连续比较不合法。
  187. // Warning: The line below will compile, but it means `(0 < a) < 2`.
  188. // 警告:下面这行可以编译,但是含义是`(0<a) < 2`
  189. int between_0_and_2 = 0 < a < 2;
  190. // Instead use:
  191. // This expression is always true, because (0 < a) could be either 1 or 0.
  192. // In this case it's 1, because (0 < 1).
  193. // 这个表达式经常为真,因为(0<a)可以是1或者0. 在这个例子里是1,因为(0<1)。
  194. int between_0_and_2 = 0 < a && a < 2;
  195. // Logic works on ints 逻辑运算符适用于整数。
  196. !3; // => 0 (Logical not) 非
  197. !0; // => 1
  198. 1 && 1; // => 1 (Logical and) 与
  199. 0 && 1; // => 0
  200. 0 || 1; // => 1 (Logical or) 或
  201. 0 || 0; // => 0
  202. // Conditional ternary expression ( ? : ) 条件表达式
  203. int e = 5;
  204. int f = 10;
  205. int z;
  206. z = (e > f) ? e : f; // => 10 "if e > f return e, else return f."
  207. // 10 “若e>f 返回 e, 否则返回 f".
  208. // Increment and decrement operators: 增 和 减
  209. int j = 0;
  210. int s = j++; // Return j THEN increase j. (s = 0, j = 1) 返回j 然后增加j的值
  211. s = ++j; // Increase j THEN return j. (s = 2, j = 2) 增加j的值然后返回j.
  212. // same with j-- and --j 同理
  213. // Bitwise operators! 位运算
  214. ~0x0F; // => 0xFFFFFFF0 (bitwise negation, "1's complement", example result for 32-bit int) 取反
  215. 0x0F & 0xF0; // => 0x00 (bitwise AND) 与
  216. 0x0F | 0xF0; // => 0xFF (bitwise OR) 或
  217. 0x04 ^ 0x0F; // => 0x0B (bitwise XOR) 异或
  218. 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) 左移
  219. 0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) 右移
  220. // Be careful when shifting signed integers - the following are undefined:
  221. // - shifting into the sign bit of a signed integer (int a = 1 << 31)
  222. // - left-shifting a negative number (int a = -1 << 2)
  223. // - shifting by an offset which is >= the width of the type of the LHS:
  224. // int a = 1 << 32; // UB if int is 32 bits wide
  225. // 对有符号整数移位要小心--以下未定义:
  226. // 有符号整数位移至符号位 int a = 1 << 32
  227. // 左移位一个负数 ( int a = -1 << 2)
  228. // 移位超过或等于该类型数值的长度。
  229. // int a = 1 << 32; 假定int32位
  230. ///////////////////////////////////////
  231. // Control Structures 控制结构
  232. ///////////////////////////////////////
  233. if (0) {
  234. printf("I am never run\n");
  235. } else if (0) {
  236. printf("I am also never run\n");
  237. } else {
  238. printf("I print\n");
  239. }
  240. // While loops exist
  241. // while循环
  242. int ii = 0;
  243. while (ii < 10) { //ANY value less than ten is true. 任何小于10的值均为真
  244. printf("%d, ", ii++); // ii++ increments ii AFTER using its current value.
  245. // ii++在取值后自增。
  246. } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
  247. printf("\n");
  248. int kk = 0;
  249. do {
  250. printf("%d, ", kk);
  251. } while (++kk < 10); // ++kk increments kk BEFORE using its current value.
  252. // ++kk 先自增,再被取值。
  253. // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
  254. printf("\n");
  255. // For loops too For 循环。
  256. int jj;
  257. for (jj=0; jj < 10; jj++) {
  258. printf("%d, ", jj);
  259. } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
  260. printf("\n");
  261. // *****NOTES*****: 注意
  262. // Loops and Functions MUST have a body. If no body is needed:
  263. // 循环和函数必须有主体部分,如果不需要主体,使用分号代表主体(null语句)
  264. int i;
  265. for (i = 0; i <= 5; i++) {
  266. ; // use semicolon to act as the body (null statement)
  267. }
  268. // Or
  269. for (i = 0; i <= 5; i++);
  270. // branching with multiple choices: switch()
  271. // 多重分支:switch()
  272. switch (a) {
  273. case 0: // labels need to be integral *constant* expressions (such as enums)
  274. // 标签必须是整数常量表达式
  275. printf("Hey, 'a' equals 0!\n");
  276. break; // if you don't break, control flow falls over labels
  277. // 如果不使用break, 控制结构会继续执行下面的标签
  278. case 1:
  279. printf("Huh, 'a' equals 1!\n");
  280. break;
  281. // Be careful - without a "break", execution continues until the next "break" is reached.
  282. // 小心,没有"break", 会执行到下一个"break"达到
  283. case 3:
  284. case 4:
  285. printf("Look at that.. 'a' is either 3, or 4\n");
  286. break;
  287. default:
  288. // if `some_integral_expression` didn't match any of the labels
  289. // 如果没有匹配任何标签。
  290. fputs("Error!\n", stderr);
  291. exit(-1);
  292. break;
  293. }
  294. /*
  295. using "goto" in C 在C语言中使用"goto"
  296. */
  297. typedef enum { false, true } bool;
  298. // for C don't have bool as data type before C99 :(
  299. // 在C99之前没有bool类型
  300. bool disaster = false;
  301. int i, j;
  302. for(i=0;i<100;++i)
  303. for(j=0;j<100;++j)
  304. {
  305. if((i + j) >= 150)
  306. disaster = true;
  307. if(disaster)
  308. goto error;
  309. }
  310. error :
  311. printf("Error occurred at i = %d & j = %d.\n", i, j);
  312. /*
  313. https://ideone.com/GuPhd6
  314. this will print out "Error occurred at i = 51 & j = 99."
  315. */
  316. ///////////////////////////////////////
  317. // Typecasting 类型转化
  318. ///////////////////////////////////////
  319. // Every value in C has a type, but you can cast one value into another type
  320. // if you want (with some constraints).
  321. // 在C中每个变量值都有类型,你可以把一个值转换成另外一个类型,如果你想(有一定限制)
  322. int x_hex = 0x01; // You can assign vars with hex literals 可以用16进制字面值复制。
  323. // Casting between types will attempt to preserve their numeric values
  324. //类型转换时,数字本身的值会被保留下来。
  325. printf("%d\n", x_hex); // => Prints 1
  326. printf("%d\n", (short) x_hex); // => Prints 1
  327. printf("%d\n", (char) x_hex); // => Prints 1
  328. // Types will overflow without warning
  329. // 类型转换时可能会溢出,而且没有警告。
  330. printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long)
  331. // char的最大值是255,假定char为8位长。
  332. // For determining the max value of a `char`, a `signed char` and an `unsigned char`,
  333. // respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from <limits.h>
  334. // 使用<limits.h>提供的CHAR_MAX, SCHAR_MAX和 UCHAR_MAX 宏确定'char','signed char'和'unsigned char'的最大值。
  335. // Integral types can be cast to floating-point types, and vice-versa.
  336. // 整数类型可以转换成浮点类型,反过来也一样。
  337. printf("%f\n", (float)100); // %f formats a float 单精度浮点
  338. printf("%lf\n", (double)100); // %lf formats a double 格式化双精度浮点
  339. printf("%d\n", (char)100.0);
  340. ///////////////////////////////////////
  341. // Pointers 指针
  342. ///////////////////////////////////////
  343. // A pointer is a variable declared to store a memory address. Its declaration will
  344. // also tell you the type of data it points to. You can retrieve the memory address
  345. // of your variables, then mess with them.
  346. // 指针变量是用来存储内存地址的变量,指针变量的声明也会告诉指向数据的类型,你可以使用得到你的变量的地址,并把它们搞乱。
  347. int x = 0;
  348. printf("%p\n", (void *)&x); // Use & to retrieve the address of a variable 使用&来得到变量地址
  349. // (%p formats an object pointer of type void *)
  350. // => Prints some address in memory;
  351. // (%p 格式化一个类型为 void *的指针)
  352. // => 打印某个内存地址
  353. // Pointers start with * in their declaration
  354. // 指针类型在声明中以*开头
  355. int *px, not_a_pointer; // px is a pointer to an int , px 是一个指向int型的指针
  356. px = &x; // Stores the address of x in px , 把x的地址保存到px中。
  357. printf("%p\n", (void *)px); // => Prints some address in memory, 打印内存中的某个地址
  358. printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer));
  359. // => Prints "8, 4" on a typical 64-bit system
  360. // 在64位系统上打印为“8,4”
  361. // To retrieve the value at the address a pointer is pointing to,
  362. // put * in front to dereference it.
  363. // Note: yes, it may be confusing that '*' is used for _both_ declaring a
  364. // pointer and dereferencing it.
  365. // 要得到某个指针指向的内容的值,可以在指针前加一个*来取得(取消引用) 注意:是的,这可能让人困惑,'*'在用来声明一个指针的同事取消引用它。
  366. printf("%d\n", *px); // => Prints 0, the value of x。 输出0,即x的值
  367. // You can also change the value the pointer is pointing to.
  368. // We'll have to wrap the dereference in parenthesis because
  369. // ++ has a higher precedence than *.
  370. // 你也可以改变指针所指向的值,此时你需要取消引用上添加括号,因为++比*的优先级更高。
  371. (*px)++; // Increment the value px is pointing to by 1
  372. //把px所指向的值增加1
  373. printf("%d\n", *px); // => Prints 1
  374. printf("%d\n", x); // => Prints 1
  375. // Arrays are a good way to allocate a contiguous block of memory
  376. //数组是分配一系列连续空间的常用方式
  377. int x_array[20]; //declares array of size 20 (cannot change size) 声明20个整数元素的数组
  378. int xx;
  379. for (xx = 0; xx < 20; xx++) {
  380. x_array[xx] = 20 - xx;
  381. } // Initialize x_array to 20, 19, 18,... 2, 1
  382. // Declare a pointer of type int and initialize it to point to x_array
  383. // 声明一个整型的指针,并初始化为指向 x_array.
  384. int* x_ptr = x_array;
  385. // x_ptr now points to the first element in the array (the integer 20).
  386. // This works because arrays often decay into pointers to their first element.
  387. // For example, when an array is passed to a function or is assigned to a pointer,
  388. // it decays into (implicitly converted to) a pointer.
  389. // Exceptions: when the array is the argument of the `&` (address-of) operator:
  390. // x_ptr 现在指向了数组的第一个元素(即整数20).
  391. // 这是因为数组通常衰减为指向它们的第一个元素的指针。
  392. // 例如,当一个数组被传递给函数或绑定一个指针时,它衰减为(隐形转化为)一个指针。
  393. //例外:当数组是'&'操作符的参数
  394. int arr[10];
  395. int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`!
  396. // It's of type "pointer to array" (of ten `int`s).
  397. // or when the array is a string literal used for initializing a char array:
  398. // &arr的类型不是'int *'! 它的类型是指向数组的指针(数组由10个int组成,或者当数组是字符串字面量(初始化字符数组)
  399. char otherarr[] = "foobarbazquirk";
  400. // or when it's the argument of the `sizeof` or `alignof` operator:
  401. // 或者当它是'sizeof'或'alignof'的参数时:
  402. int arraythethird[10];
  403. int *ptr = arraythethird; // equivalent with int *ptr = &arr[0]; 等价于 int *ptr = &arr[0];
  404. printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr);
  405. // probably prints "40, 4" or "40, 8"
  406. // 应该会输出“40,4" 或 ”40,8“
  407. // Pointers are incremented and decremented based on their type
  408. // (this is called pointer arithmetic)
  409. //指针的增减多少是根据它的类型而定,成为指针运算。
  410. printf("%d\n", *(x_ptr + 1)); // => Prints 19
  411. printf("%d\n", x_array[1]); // => Prints 19
  412. // You can also dynamically allocate contiguous blocks of memory with the
  413. // standard library function malloc, which takes one argument of type size_t
  414. // representing the number of bytes to allocate (usually from the heap, although this
  415. // may not be true on e.g. embedded systems - the C standard says nothing about it).
  416. // 你也可以通过标准库函数malloc来实现动态分配,这个函数接收一个代表容量的参数,参数类型为'size_t',系统一般会从堆区heap分配指定容量字节大小的空间(在一些系统,例如嵌入系统中这一点不一定成立,C标准对此未提及)
  417. int *my_ptr = malloc(sizeof(*my_ptr) * 20);
  418. for (xx = 0; xx < 20; xx++) {
  419. *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
  420. } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) 初始化内存为20,19,18,17...2,1(类型为int)
  421. // Be careful passing user-provided values to malloc! If you want
  422. // to be safe, you can use calloc instead (which, unlike malloc, also zeros out the memory)
  423. //小心传给malloc的值,为了安全,可以用calloc代替(不像malloc)会初始化内存为0.
  424. int* my_other_ptr = calloc(20, sizeof(int));
  425. // Note that there is no standard way to get the length of a
  426. // dynamically allocated array in C. Because of this, if your arrays are
  427. // going to be passed around your program a lot, you need another variable
  428. // to keep track of the number of elements (size) of an array. See the
  429. // functions section for more info.
  430. //注意,没有标准方法来得到C中动态分配的数组长度,如果你打算传递到程序中更多信息,需要另外一个变量来保存数组的元素个数,看functions一节来得到更多描述。
  431. size_t size = 10;
  432. int *my_arr = calloc(size, sizeof(int));
  433. // Add an element to the array
  434. size++;
  435. my_arr = realloc(my_arr, sizeof(int) * size);
  436. if (my_arr == NULL) {
  437. //Remember to check for realloc failure!
  438. return
  439. }
  440. my_arr[10] = 5;
  441. // Dereferencing memory that you haven't allocated gives
  442. // "unpredictable results" - the program is said to invoke "undefined behavior"
  443. // 反引用尚未分配的内存引发不可预测的结果,程序可能引发未知行为。
  444. printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash. 不知道会打印什么,可能崩溃。
  445. // When you're done with a malloc'd block of memory, you need to free it,
  446. // or else no one else can use it until your program terminates
  447. // (this is called a "memory leak"):
  448. // 如果你用malloc分配了内存,你需要释放。或者等程序结束(这叫内存泄露)
  449. free(my_ptr);
  450. // Strings are arrays of char, but they are usually represented as a
  451. // pointer-to-char (which is a pointer to the first element of the array).
  452. // It's good practice to use `const char *' when referring to a string literal,
  453. // since string literals shall not be modified (i.e. "foo"[0] = 'a' is ILLEGAL.)
  454. // 字符串通常是字符数组,但是经常用字符指针表示(它是指向数组的第一个元素的指针); 一个优良的实践是使用'const char *’来引用一个字符串字面量,因为字符串字面量不应当被修改(即“foo"[0]='a'非法)
  455. const char *my_str = "This is my very own string literal";
  456. printf("%c\n", *my_str); // => 'T'
  457. // This is not the case if the string is an array (potentially initialized with a string literal) that resides in writable memory, as in:
  458. // 如果字符串是位于可写的内存数组中,(多半是用字符串字面量初始化的),则不是这种情况,如下:
  459. char foo[] = "foo";
  460. foo[0] = 'a'; // this is legal, foo now contains "aoo"
  461. // 这是合法的,现在foo为"aoo"
  462. function_1();
  463. } // end main function
  464. ///////////////////////////////////////
  465. // Functions 函数
  466. ///////////////////////////////////////
  467. // Function declaration syntax:
  468. // <return type> <function name>(<args>)
  469. // 函数声明语法:<返回值类型><函数名称>(<参数>)
  470. int add_two_ints(int x1, int x2)
  471. {
  472. return x1 + x2; // Use return to return a value
  473. // 使用return来返回一个值
  474. }
  475. /*
  476. Functions are call by value. When a function is called, the arguments passed to
  477. the function are copies of the original arguments (except arrays). Anything you
  478. do to the arguments in the function do not change the value of the original
  479. argument where the function was called.
  480. Use pointers if you need to edit the original argument values.
  481. 函数是按值传递的。当 调用一个函数,参数是原有值的拷贝(数组除外)。你在函数内对参数所进行的操作,不会改变该参数原有的值。
  482. 当你需要修改原始参数值是可以使用指针。
  483. Example: in-place string reversal
  484. 例子:字符串本身翻转
  485. */
  486. // A void function returns no value
  487. // void类型函数无返回值
  488. void str_reverse(char *str_in)
  489. {
  490. char tmp;
  491. int ii = 0;
  492. size_t len = strlen(str_in); // `strlen()` is part of the c standard library C标准库函数
  493. for (ii = 0; ii < len / 2; ii++) {
  494. tmp = str_in[ii];
  495. str_in[ii] = str_in[len - ii - 1]; // ii-th char from end
  496. str_in[len - ii - 1] = tmp;
  497. }
  498. }
  499. //NOTE: string.h header file needs to be included to use strlen()
  500. //注意:string.h头文件需要包括来使用strlen()
  501. /*
  502. char c[] = "This is a test.";
  503. str_reverse(c);
  504. printf("%s\n", c); // => ".tset a si sihT"
  505. */
  506. /*
  507. as we can return only one variable
  508. to change values of more than one variables we use call by reference
  509. 因为我们只能返回一个变量。要改变多个变量时使用引用
  510. */
  511. void swapTwoNumbers(int *a, int *b)
  512. {
  513. int temp = *a;
  514. *a = *b;
  515. *b = temp;
  516. }
  517. /*
  518. int first = 10;
  519. int second = 20;
  520. printf("first: %d\nsecond: %d\n", first, second);
  521. swapTwoNumbers(&first, &second);
  522. printf("first: %d\nsecond: %d\n", first, second);
  523. // values will be swapped 值交换了。
  524. */
  525. /*
  526. With regards to arrays, they will always be passed to functions as pointers. Even if you statically allocate an array like `arr[10]`,
  527. it still gets passed as a pointer to the first element in any function calls.
  528. Again, there is no standard way to get the size of a dynamically allocated array in C.
  529. 对于数组,经常是作为指针传递给函数,即使你静态分配一个数组像'arr[10]',在任何函数中它仍然是通过指向第一个元素的指针传递的。
  530. 再一次,没有标准方法来得到C中分配的动态数组的大小。
  531. */
  532. // Size must be passed! 大小必须传递
  533. // Otherwise, this function has no way of knowing how big the array is.
  534. //否则,函数不知道数组多大。
  535. void printIntArray(int *arr, size_t size) {
  536. int i;
  537. for (i = 0; i < size; i++) {
  538. printf("arr[%d] is: %d\n", i, arr[i]);
  539. }
  540. }
  541. /*
  542. int my_arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  543. int size = 10;
  544. printIntArray(my_arr, size);
  545. // will print 会打印"arr[0] is: 1" etc
  546. */
  547. // if referring to external variables outside function, you should use the extern keyword.
  548. // 如果引用函数function外部的变量,必须使用extern关键字。
  549. int i = 0;
  550. void testFunc() {
  551. extern int i; //i here is now using external variable i
  552. }
  553. // make external variables private to source file with static:
  554. // 使用static确保external变量为源文件私有
  555. static int j = 0; //other files using testFunc2() cannot access variable j
  556. // 其他使用testFunc2()的文件无法访问变量j.
  557. void testFunc2() {
  558. extern int j;
  559. }
  560. //**You may also declare functions as static to make them private**
  561. // 你同样可以声明函数为static**
  562. ///////////////////////////////////////
  563. // User-defined types and structs 用户自定义类型和结构
  564. ///////////////////////////////////////
  565. // Typedefs can be used to create type aliases
  566. // Typedefs 可以创建类型别名
  567. typedef int my_type;
  568. my_type my_type_var = 0;
  569. // Structs are just collections of data, the members are allocated sequentially,in the order they are written:
  570. // struct是数据的集合,成员按照编写的顺序依序分配。
  571. struct rectangle {
  572. int width;
  573. int height;
  574. };
  575. // It's not generally true that sizeof(struct rectangle) == sizeof(int) + sizeof(int)
  576. // due to potential padding between the structure
  577. members (this is for alignment reasons). [1]
  578. // 一般而言,以下断言不成立: sizeof(struct rectangle) == sizeof(int) + sizeof(int) 这是因为structure成员之间可能存在潜在的间隙(为了对齐)[1]
  579. void function_1()
  580. {
  581. struct rectangle my_rec;
  582. // Access struct members with .
  583. // 通过 . 来访问结构中的数据
  584. my_rec.width = 10;
  585. my_rec.height = 20;
  586. // You can declare pointers to structs
  587. // 你也可以声明指向结构体的指针
  588. struct rectangle *my_rec_ptr = &my_rec;
  589. // Use dereferencing to set struct pointer members...
  590. // 通过取消引用来改变结构体的成员...
  591. (*my_rec_ptr).width = 30;
  592. // ... or even better: prefer the -> shorthand for the sake of readability
  593. // ... 或者用 -> 操作符作为简写提高可读性
  594. my_rec_ptr->height = 10; // Same as 等同 (*my_rec_ptr).height = 10;
  595. }
  596. // You can apply a typedef to a struct for convenience
  597. // 你也可以用typedef来给一个结构体起一个别名
  598. typedef struct rectangle rect;
  599. int area(rect r)
  600. {
  601. return r.width * r.height;
  602. }
  603. // if you have large structs, you can pass them "by pointer" to avoid copying the whole struct:
  604. // 如果sturct较大,你可以通过指针传递,避免复制整个struct.
  605. int areaptr(const rect *r)
  606. {
  607. return r->width * r->height;
  608. }
  609. ///////////////////////////////////////
  610. // Function pointers 函数指针
  611. ///////////////////////////////////////
  612. /*
  613. At run time, functions are located at known memory addresses. Function pointers are
  614. much like any other pointer (they just store a memory address), but can be used
  615. to invoke functions directly, and to pass handlers (or callback functions) around.
  616. However, definition syntax may be initially confusing.
  617. 在运行时,函数本身也被存放到某块内存区域当中,函数指针就像其他指针一样(不过是存储一个内存地址)但是却可以用来直接调用,并且可以四处传递回调函数,然而,初看定义的语法令人有些迷惑。
  618. Example: use str_reverse from a pointer
  619. 例子:通过指针调用 str_reverse
  620. */
  621. void str_reverse_through_pointer(char *str_in) {
  622. // Define a function pointer variable, named f.
  623. // 定义一个函数指针 f
  624. void (*f)(char *); // Signature should exactly match the target function. 签名一定要与目标函数相同
  625. f = &str_reverse; // Assign the address for the actual function (determined at run time)
  626. // 将函数的地址在运行时赋予指针。
  627. // f = str_reverse; would work as well - functions decay into pointers, similar to arrays
  628. // f = str_reverse; 也可以,类似数组,函数衰减decay成指针
  629. (*f)(str_in); // Just calling the function through the pointer 通过指针调用
  630. // f(str_in); // That's an alternative but equally valid syntax for calling it. 等价于这种调用方式
  631. }
  632. /*
  633. As long as function signatures match, you can assign any function to the same pointer.
  634. Function pointers are usually typedef'd for simplicity and readability, as follows:
  635. 只要函数签名是正确的,任何时候都能将任何函数赋予给某个函数指针,为了可读性和简洁性,函数指针经常和typedef搭配使用:
  636. */
  637. typedef void (*my_fnp_type)(char *);
  638. // Then used when declaring the actual pointer variable:
  639. // 实际声明函数指针会这么用:
  640. // ...
  641. // my_fnp_type f;
  642. //Special characters:
  643. // 特殊字符
  644. /*
  645. '\a'; // alert (bell) character
  646. '\n'; // newline character 换行
  647. '\t'; // tab character (left justifies text)
  648. '\v'; // vertical tab
  649. '\f'; // new page (form feed)
  650. '\r'; // carriage return 回车
  651. '\b'; // backspace character 退格
  652. '\0'; // NULL character. Usually put at end of strings in C. 通常置于字符串最后。 按照惯例 \0用于标记字符串的末尾
  653. // hello\n\0. \0 used by convention to mark end of string.
  654. '\\'; // backslash 反斜杠
  655. '\?'; // question mark 问号
  656. '\''; // single quote 单引号
  657. '\"'; // double quote 双引号
  658. '\xhh'; // hexadecimal number. Example: '\xb' = vertical tab character 十六进制数字。
  659. '\0oo'; // octal number. Example: '\013' = vertical tab character // 十进制数字
  660. //print formatting: 打印格式:
  661. "%d"; // integer 整数
  662. "%3d"; // integer with minimum of length 3 digits (right justifies text) 3位以上整数(右对齐文本)
  663. "%s"; // string 字符串
  664. "%f"; // float
  665. "%ld"; // long
  666. "%3.2f"; // minimum 3 digits left and 2 digits right decimal float 左3位以上,右2位以上十进制浮点
  667. "%7.4s"; // (can do with strings too) 字符串同样适用
  668. "%c"; // char 字符
  669. "%p"; // pointer 指针
  670. "%x"; // hexadecimal 十六进制
  671. "%o"; // octal 八进制
  672. "%%"; // prints % 打印 %
  673. */
  674. ///////////////////////////////////////
  675. // Order of Evaluation 演算优先级
  676. ///////////////////////////////////////
  677. //---------------------------------------------------//
  678. // Operators | Associativity //
  679. //---------------------------------------------------//
  680. // () [] -> . | left to right //
  681. // ! ~ ++ -- + = *(type)sizeof | right to left //
  682. // * / % | left to right //
  683. // + - | left to right //
  684. // << >> | left to right //
  685. // < <= > >= | left to right //
  686. // == != | left to right //
  687. // & | left to right //
  688. // ^ | left to right //
  689. // | | left to right //
  690. // && | left to right //
  691. // || | left to right //
  692. // ?: | right to left //
  693. // = += -= *= /= %= &= ^= |= <<= >>= | right to left //
  694. // , | left to right //
  695. //---------------------------------------------------//
  696. /******************************* Header Files **********************************
  697. Header files are an important part of C as they allow for the connection of C
  698. source files and can simplify code and definitions by separating them into
  699. separate files.
  700. Header files are syntactically similar to C source files but reside in ".h"
  701. files. They can be included in your C source file by using the precompiler
  702. command #include "example.h", given that example.h exists in the same directory
  703. as the C file.
  704. 头文件是C的重要一部分,可以链接源文件,并且简化代码和定义,通过将他们分开。
  705. 头文件在语法上与C源文件类似,但位于".h"文件。他们可以通过使用预编译命令#include "example.h" 来包含在你的C源代码文件里,假设 example.h 和 C文件一样存在于同样目录中
  706. */
  707. /* A safe guard to prevent the header from being defined too many times. This happens in the case of circle dependency, the contents of the header is already defined.
  708. 当循环依赖时,头文件的内容已经定义,为了避免头文件被定义多次,有个安全措施
  709. */
  710. #ifndef EXAMPLE_H /* if EXAMPLE_H is not yet defined. */
  711. #define EXAMPLE_H /* Define the macro EXAMPLE_H. */
  712. /* 如果 EXAMPLE_H 没有定义,定义宏 EXAMPLE_H */
  713. /* Other headers can be included in headers and therefore transitively included into files that include this header.
  714. 其他头文件可以被包含在 头文件里,因此可以传递性地包含在这个头文件里。
  715. */
  716. #include <string.h>
  717. /* Like c source files macros can be defined in headers and used in files that include this header file. C源代码文件里的宏可以在头文件里定义,并且在文件中使用头文件里定义的宏
  718. */
  719. #define EXAMPLE_NAME "Dennis Ritchie"
  720. /* Function macros can also be defined. */
  721. // 函数宏可以被定义
  722. #define ADD(a, b) ((a) + (b))
  723. /* Notice the parenthesis surrounding the arguments -- this is important to ensure that a and b don't get expanded in an unexpected way (e.g. consider MUL(x, y) (x * y); MUL(1 + 2, 3) would expand to (1 + 2 * 3), yielding an incorrect result)
  724. 注意参数周围的括号,这对于确保a和b不会以意外的方式被扩展很重要(例如考虑 MUL(x,y)(x *y); MUL(1+2,3)可能会扩展到(1+2*3)产生错误的结果)
  725. */
  726. /* Structs and typedefs can be used for consistency between files.
  727. 结构体和typedefs可以用来确保文件间的一致性
  728. */
  729. typedef struct Node
  730. {
  731. int val;
  732. struct Node *next;
  733. } Node;
  734. /* So can enumerations. 枚举也是如此 */
  735. enum traffic_light_state {GREEN, YELLOW, RED};
  736. /* Function prototypes can also be defined here for use in multiple files, but it is bad practice to define the function in the header. Definitions should instead be put in a C file.
  737. 函数原型可 被定义用于多个文件中,但是定义在头文件中不好,应该在C文件中
  738. */
  739. Node createLinkedList(int *vals, int len);
  740. /* Beyond the above elements, other definitions should be left to a C source file. Excessive includes or definitions should, also not be contained in a header file but instead put into separate headers or a C file.
  741. 除上述元素外,其他定义应留给C源文件。 过多的包含或定义应该也不包含在头文件中,而是放入单独的头文件或C文件中。
  742. */
  743. #endif /* End of the if precompiler directive. 指令if预编译结束 */

Further Reading 更多阅读

Best to find yourself a copy of K&R, aka “The C Programming Language” It is the book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it’s ancient and it contains some inaccuracies (well, ideas that are not considered good anymore) or now-changed practices.

Another good resource is Learn C The Hard Way.

If you have a question, read the compl.lang.c Frequently Asked Questions.

It’s very important to use proper spacing, indentation and to be consistent with your coding style in general. Readable code is better than clever code and fast code. For a good, sane coding style to adopt, see the Linux kernel coding style.

Other than that, Google is your friend.

最好找一本 K&R, aka “The C Programming Language”, “C程序设计语言”。它是关于C最重要的一本书,由C的创作者撰写。不过需要留意的是它比较古老了,因此有些不准确的地方。

另一个比较好的资源是 Learn C the hard way

如果你有问题,请阅读compl.lang.c Frequently Asked Questions

使用合适的空格、缩进,保持一致的代码风格非常重要。可读性强的代码比聪明的代码、快速的代码更重要。可以参考下Linux内核编码风格 。 除了这些,多多Google吧

[1]Why isn’t sizeof for a struct equal to the sum of sizeof of each member?

参考资料

Y分钟学习C语言
https://www.kancloud.cn/kancloud/learnxinyminutes/58928

learn c in y minutes
https://learnxinyminutes.com/docs/c/

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注