MARS MIPS 和结构节点 [英] MARS MIPS and struct nodes

查看:25
本文介绍了MARS MIPS 和结构节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typedef struct node {    
    int data;    
    struct node *next;    
} nodeL; 

假设我想用 MIPS 汇编语言翻译上述声明,我该怎么做?除了分配内存(使用 syscall 9),这是在 .text 段中完成的,.data 段怎么样?另外,对齐怎么样?

Assuming I want to translate the above declaration in MIPS assembly language, how am I supposed to do it? Apart from allocating memory (using syscall 9), which is done in the .text segment, what about the .data segment? Also, what about alignment?

推荐答案

在提到代码之前,你需要明确你要创建的结构是静态数据(数据段)、本地数据(堆栈)还是动态数据分配的数据(堆).每个都有不同的分配方式.

Before even mentioning code, you need to clarify whether the struct you want to create will be static data (data segment), local data (stack), or dynamically allocated data (heap). There are different ways to allocate each.

但在讨论之前,您需要做的第一件事是确定结构实例的布局.至少可以是:

But before discussing that, the very first thing you need to do is determine the layout of the struct instance. At the very least it could be:

------------------
| data - 32-bits |
------------------
| next - 32-bits |
------------------

要静态创建实例,只需:

To create an instance statically, it's simply:

    .data
    .align 2
anInstance:     .word   0,0

在堆上:

    .text
Allocator.newNode:
    li $a0, 8           #allocate 8 bytes
    li $v0, 9
    syscall             #returns word-aligned ptr
    jr $ra

如果放置在堆栈上,只需为其分配 8 个字节.

If placing on the stack, simply allocate 8 bytes for it.

更简洁的方法是使用基于原型的方法.

A cleaner way is to use a prototype-based method.

您的对象布局变为:

------------------
| size - 32-bits |
------------------
| atr 1 - 32-bits|
------------------
| atr 2 - 32-bits|
------------------
.
.
.
------------------
| atr n - 32-bits|
------------------

对于每个结构,您创建一个原型,分配例程将使用该原型来创建实例.

For each struct, you create a prototype which the allocation routine will use to create the instance.

    .data
ListProto:      .word   8,0     #size, head ptr
NodeProto:      .word   12,0,0  #size, data, next ptr    

    .text
main:
    la $a0, ListProto
    jal Allocator.newObject     #create new list instance

    la $a0, NodeProto
    jal Allocator.newObject     #create new node instance

Allocator.newObject:
    lw $a0, 0($a0)      #a0 = object size
    li $v0, 9
    syscall
    jr $ra

您是否希望实例实际保留大小字段取决于您.使用这种方法,您可以简单地添加原型,仅此而已.

Whether you want the instance to actually keep a size field is up to you. With that approach you can simply add prototypes and that's it.

这篇关于MARS MIPS 和结构节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆