Basic Pascal Tutorial/Chapter 5/1-dimensional arrays/zh CN: what changed
Revision 2 to 3. Removed lines have a minus sign; added lines have a plus sign.
| Old | New | Line | |
|---|---|---|---|
| 1 | 1 | 5C - 一维数组 (原作者: Tao Yue, 状态: 未更改) | |
| 2 | 2 | ||
| 3 | 3 | 假设你需要使用5000个整数,你会如何存储?你可以定义5000个变量: | |
| 4 | 4 | ||
| 5 | - | ||
| 5 | + | ```text | |
| 6 | 6 | aa, ab, ac, ad, ... aaa, aab, ... aba, ... | |
| 7 | 7 | ``` | |
| 8 | 8 | ||
| 9 | 9 | 但这很繁琐(声明这些变量后,你需要读取每个变量)。 | |
| 10 | 10 | ||
| 11 | 11 | 一个数组包含多个存储空间,类型相同。你只需要指定数组名和下标就可以使用了: | |
| 12 | 12 | ||
| 13 | 13 | ``` pascal | |
| 14 | 14 | type | |
| 15 | 15 | typename = array [下标类型] of 数据类型; | |
| 16 | 16 | ``` | |
| 17 | 17 | ||
| 18 | 18 | 数据类型任意,甚至是一个数组。方括号中的“下标类型”可以是任何的顺序类型,即可以是整型,布尔型,字符类型,枚举类型,子界类型。 | |
| 19 | 19 | ||
| 20 | 20 | ``` pascal | |
| 21 | 21 | type | |
| 22 | 22 | enum_type = 1..50; | |
| 23 | 23 | arraytype = array [enum_type] of integer; | |
| 24 | 24 | ``` | |
| 25 | 25 | ||
| 26 | 26 | is equivalent to | |
| 27 | 27 | ||
| 28 | 28 | ``` pascal | |
| 29 | 29 | type | |
| 30 | 30 | arraytype = array [1..50] of integer; | |
| 31 | 31 | ``` | |
| 32 | 32 | ||
| 33 | 33 | 注:在此之前,程序员需要自己处理字符串存储问题。通过声明: | |
| 34 | 34 | ||
| 35 | 35 | ``` pascal | |
| 36 | 36 | type | |
| 37 | 37 | String = packed array [0..255] of char; | |
| 38 | 38 | ``` | |
| 39 | 39 | ||
| 40 | 40 | 使用某种特殊字符来表示字符串结束,大多使用空字符(0或ord(0)),packed指定了占用空间。 | |
| 41 | 41 | ||
| 42 | 42 | 在C或C++编程语言中,把200个字符存入长度为150的数组,会造成[缓冲区溢出](http://zh.wikipedia.org/zh-cn/%E7%BC%93%E5%86%B2%E5%8C%BA%E6%BA%A2%E5%87%BA)。如果缓冲区被覆盖并包含可执行代码,那么,攻击者将会设法进入你的系统。这就是Slammer蠕虫病毒猖獗的原因。试试在Pascal中会发什么。 | |
| 43 | 43 | ||
| 44 | 44 | 如果你需要在程序中存储大量数据,数据的下标可以循环读取出来,例如: | |
| 45 | 45 | ||
| 46 | 46 | ``` pascal | |
| 47 | 47 | type | |
| 48 | 48 | arraytype = array[1..50] of integer; | |
| 49 | 49 | ||
| 50 | 50 | var | |
| 51 | 51 | myarray : arraytype; | |
| 52 | 52 | ``` | |
| 53 | 53 | ||
| 54 | 54 | 使用: | |
| 55 | 55 | ||
| 56 | 56 | ``` pascal | |
| 57 | 57 | for count := 1 to 50 do | |
| 58 | 58 | read (myarray[count]); | |
| 59 | 59 | ``` | |
| 60 | 60 | ||
| 61 | 61 | 使用数组时,使用方括号`[ ]`括起下标。 | |
| 62 | 62 | ||
| 63 | 63 | ``` pascal | |
| 64 | 64 | myarray[5] := 6; | |
| 65 | 65 | ``` | |
| 66 | 66 | ||
| 67 | 67 | | | | | | |
| 68 | 68 | |----|----|----| | |
| 69 | 69 | | [[Basic Pascal Tutorial/Chapter 5/Subranges/zh CN|上一页]] | [[Basic Pascal Tutorial/Contents/zh CN|目录]] | [[Basic Pascal Tutorial/Chapter 5/Multidimensional arrays/zh CN|下一页]] | | |
| 70 | 70 | ||
| 71 | 71 | --- | |
| 72 | 72 | *From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 5/1-dimensional arrays/zh CN", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* | |
| 73 | 73 | Category: zh |
