我的一个练习是将数组的值设置为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年来忘记的事情!

10-07 22:49