【问题标题】:Assembly + C - Sorting Structures汇编 + C - 排序结构
【发布时间】:2016-10-16 03:55:03
【问题描述】:

我正在开发一个同时使用 x86 汇编 (NASM) 和 C 的项目。有一个用 Assembly 编写的子例程,它使用索引寻址模式来确定某个年份 (int) 是否小于或大于另一个年份,然后根据结果返回 -1、1 或 0。看来,如果我输入超过 4 或 5 条记录,则无法正确排序。我花了几个小时通过 gdb 运行它,并发现在第一次递增 j 的最后一次迭代中(在 i 递增之前),它运行交换,即使它不应该运行,但我不确定如何修复它。提前感谢您的任何想法。

---C代码---

【问题讨论】:

  • 为什么不将函数参数传递给cmpbook,而不是使用两个全局变量?这真的很难看(而且有点慢)。相关:此评论是虚假的:mov esi, [book1] ; store the pointers to each book。这是一个加载指令(内存源,而不是内存目标)。
  • uses indexed addressing modes to figure out if a certain year (int) is lesser or greater than another。另一个完全虚假的描述。我真的很好奇你发明了什么样的查找表来比较整数和地址数学,而不是只使用cmp,但事实证明你只是使用[reg + displacement]寻址模式来访问结构字段。
  • 您在 asm 函数的末尾缺少 ret
  • 其中一些是为我们设置的,并规定了我们能做什么和不能做什么。全局变量是其中的一部分。我们还没有学会如何在 Assembly 和 C 之间传递类似的参数。

标签: c assembly x86 nasm


【解决方案1】:

我明白了。这是因为我将 min = i 设置在错误的位置。应该是这样的:

for (i = 0; i < numBooks - 1; i++) {
          /*** WAS HERE ***/
          for (j = i + 1; j < numBooks; j++) {

            /*** SHOULD BE HERE ***/
            min = i;

            /* Copy pointers to the two books to be compared into the
            * global variables book1 and book2 for bookcmp() to see
            */
            book1 = &books[i];
            book2 = &books[j];

            cmpResult = bookcmp();
            /* bookcmp returns result in register EAX--above saves
            * it into cmpResult */

            /* book2 comes before book1, in other
            words, book1 is greater - value stored in
            eax will in this case be 1 */
            if (cmpResult == 1) {
              min = j;
            }

            if (min != i) {
              tempBook = books[i];
              books[i] = books[min];
          books[min] = tempBook;
            }

          }
        }
    }

【讨论】:

  • 你为什么不直接做if(bookcmp(&amp;books[i], &amp;books[j]) == 1) { swap books[i] with books[j] }? (仍然像您当前的代码一样使用 3 个作业)。这完全摆脱了min,将循环体大大简化为通常的比较和交换。
  • 彼得总能得到好的建议!事实上,我什至不知道这个功能。
猜你喜欢
  • 1970-01-01
  • 2020-08-23
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 2011-09-26
相关资源
最近更新 更多