c - x86-如何使用内联汇编中的for循环将值插入数组

标签 c arrays visual-c++ x86 inline-assembly

我的一个练习是将数组的值设置为0到9,并使用尽可能多的内联程序集打印和。我几乎没有内联组装的经验,并且已经用尽了我的研究,试图找到一个解决方案。
这是我目前掌握的密码。它编译没有错误,但是,当我试图运行应用程序时,它只是崩溃。我知道这是不完整的,但我不确定我的逻辑是否正确。

#include <stdio.h>

int main(int argc, char **argv)
{
    int *numbers;
    int index;

    __asm
    {
        // Set index value to 0
        mov index, 0
        // Jump to check
        jmp $CHECK_index
        // Increment the value of index by 1
        $INCREMENT_index:
            inc index
        // Check if index >= 9
        $CHECK_index:
            cmp index, 9
            jge $END_LOOP
            // Move index value to eax register
            mov eax, index
            // Move value of eax register to array
            mov numbers[TYPE numbers * eax], eax
            // Clean the stack
            add esp, 4

            jmp $INCREMENT_index

        $END_LOOP:
            add esp, 4
    }

    return 0;
}

最佳答案

我写汇编已经有很长一段时间了(20多年了),但是您不需要分配numbers数组吗?(也可以将公司转移到更干净的地方)

#include <stdio.h>

int main(int argc, char **argv)
{
    int *numbers = new int[10];   // <--- Missing allocate
    int index;

    __asm
    {
        // Set index value to 0
        mov index, 0

        // Check if index >= 9
        $CHECK_index:
            cmp index, 9
            jge $END_LOOP

            // Move index value to eax register
            mov eax, index

            // Move value of eax register to array
            mov numbers[TYPE numbers * eax], eax

            // Increment the value of index by 1
            inc index           // <---- inc is cleaner here
            jmp $CHECK_index

        $END_LOOP:
    }

    return 0;
}

注:不知道为什么你也需要移动堆栈指针(esp),但很高兴承认我20年来忘记的事情!

关于c - x86-如何使用内联汇编中的for循环将值插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48491405/

相关文章:

c++ - 从 MSVC 输出生成 Makefile 依赖项

c++ - 如何在 STL 容器中存储模板化异构对象

c++ - 无法调用 MFC ActiveX 中的方法

c - C 中的字符串提取和插入函数?

c - 使用 malloc 为结构分配内存,其中数据条目之一是指针

java - 在 JVM 之上运行/解释 C?

javascript - 根据多个特定字符从平面字符串数组创建嵌套对象

c - C 中的表达式求值

c++ - 检查 json 数组中的每个值是否存在于其他 json 文件中

sql - Postgres 将数组的每个元素(如果不存在)附加或设置到数组列