You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用基址+偏移量访问16位数组?求助数组元素访问方法

解决基址+偏移量访问数组元素的问题

嘿,问题出在你对.int类型的字节大小搞错啦!

你用.int定义的数组元素是4字节(32位)的整数,但你访问t1[1]的时候用了2(%ecx)——这个偏移量只跳了2字节,刚好是半个int元素,所以取到的是错误的数据。

正确的访问方式

每个.int元素占4字节,所以数组索引对应的偏移量应该是索引 × 4:

  • t1[0] → 0(%ecx)(或者直接(%ecx))
  • t1[1] → 4(%ecx)
  • t1[2] → 8(%ecx)

修正后的代码如下:

.section .data
t1: .int 10, 15, 25
.section .text
.globl _start
_start:
movl $t1, %ecx
movl (%ecx), %edx       # 正确获取t1[0] = 10
movl 4(%ecx), %ebx      # 正确获取t1[1] = 15
movl 8(%ecx), %eax      # 可选:获取t1[2] = 25
movl $1, %eax           # 系统调用号:exit
int $0x80

额外小技巧

如果你想用寄存器里的索引来访问数组(比如索引存在%esi里),可以用更灵活的比例寻址方式,它会自动帮你计算索引×4的偏移:

movl $1, %esi
movl (%ecx, %esi, 4), %ebx  # 等价于访问 t1[esi]

内容的提问来源于stack exchange,提问作者Niranjan M.R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:54:19