跳轉到內容

從零開始製作程式語言/陣列

來自華夏公益教科書,開放的書籍,為開放的世界

陣列宣告

[編輯 | 編輯原始碼]

陣列宣告通常與所有其他簡單變數一起完成。陣列宣告的格式本質上是對簡單變數宣告格式的擴充套件。

[format as for simple declarations][,][name of variable]['[' or ',' or ';' or '='][if '[' size of array (constant)][']'][value of array][next declaration]

示例

int a,b,arr[5],arr2[5]=(1,2,3,4,5);

(請注意,由於我們指定了 '{' 作為終止字元,因此我們將常見的 '{' 替換為 '('。如果你還沒有這樣做,你也可以使用大括號。)

演算法

[編輯 | 編輯原始碼]

該演算法是對先前演算法的延續,其中添加了以下步驟,用於檢查陣列變數並正確處理它們。

1. Get name.
2. If next character be [ then until the character be ] input character and store it in the index variable .
3. If next character be , or ; then write to data? section :
  [Name] [index] dup ?
4. Else add one character and then get character until character be ).
Then write to data section:
  [name] [value]


dup 關鍵字將複製 ? 或 0 值,用於所有成員,而無需單獨初始化每個成員。


字串的特殊情況

[編輯 | 編輯原始碼]

字串的初始化方式不同於其他陣列變數,它們可以在一塊中使用“and”同時宣告。此外,字串總是以字元 0(或 '\0')結尾。以下演算法要追加到之前的演算法中。

僅用於字串的演算法

1. if character after char array declaration not be'=' continue with rest of parent algorithm.
2. add one to index.(skip ")
3. while character not " get character and store in array.
4. write to .DATA section:
   [name] byte "[value]",0

請注意,一些彙編程式可能對初始化字串的實際大小設定限制(在 MASM 6.1 中,它是 255 位元組或 255 個單獨的字元)。請注意,初始化字串的大小僅為提供的值的大小,即在以下示例中

char str[50]="hello";

陣列 str 的大小隻有 5+1 或 6 個字元。

陣列引用

[編輯 | 編輯原始碼]

必須引用陣列才能使其有用。陣列的引用格式如下。

[...expression][array name][index of variable][...expression]

但是,組合語言不接受此格式。此外,它將索引作為起始地址後的位元組數,而不是起始地址後的變數數。

組合語言中的格式

[...instruction][array name][number of bytes after starting][...instruction]

此外,索引不能是記憶體變數,而必須是暫存器或常量。

解決方案是以下一組指令

mov ebx,[index variable(can be a constant also)]
[assignment instruction to register of type of array][array name] /[ebx * type array]/
[assignment instruction to arr[ANUM] (increment ANUM) from register used above] 

'/' 表示 '[' 的差異使用(此處,'/' 後面的括號需要複製到程式碼中)

引用演算法(在檢測到陣列變數時或在指令到達後立即執行)

1. While character not '[' and not ';' and not '{'
   increment index.
2. If character be ';' or '{' end process.
3. While character not ']' get character and store in array.
4. Get name of array.
5. Use format as given above.
6. Replace reference by arr[ANUM-1]
7. Repeat step 1
華夏公益教科書