用C语言来实现一个简单的虚拟机

2020-01-06 13:14:08丽君

接着添加指令,取出这些值,把它们加在一起并把结果压入栈中:

 

 
  1. [5, 6]   
  2. // pop the top value, store it in a variable called a  a = pop; // a contains 6 
  3. [5] // stack contents   
  4. // pop the top value, store it in a variable called b  b = pop; // b contains 5 
  5. [] // stack contents   
  6. // now we add b and a. Note we do it backwards, in addition  // this doesn't matter, but in other potential instructions 
  7. // for instance divide 5 / 6 is not the same as 6 / 5  result = b + a; 
  8. push result // push the result to the stack  [11] // stack contents 

那么我们的栈指针在哪起作用呢?栈指针(或者说sp)一般是被设置为-1,这意味着这个指针是空的。请记住一个数组是从0开始的,如果没有初始化sp的值,那么他会被设置为C编译器放在那的一个随机值。

如果我们将3个值压栈,那么sp将变成2。所以这个数组保存了三个值:

sp指向这里(sp = 2)

|

V

[1, 5, 9]

0 1 2 <- 数组下标

现在我们从栈上出栈一次,我们仅需要减小栈顶指针。比如我们接下来把9出栈,那么栈顶将变为5:

sp指向这里(sp = 1)

|

V

[1, 5]

0 1 <- 数组下标

所以,当我们想知道栈顶内容的时候,只需要查看sp的当前值。OK,你可能想知道栈是如何工作的,现在我们用C语言实现它。很简单,和ip一样,我们也应该定义一个sp变量,记得把它赋为-1!再定义一个名为stack的数组,代码如下: