2017-01-07 34 views
0

我正在編寫一個簡單的程序,它使用內聯安全地檢查給定的單詞是否是迴文。問題是它不會返回正確答案。在調試過程中我發現有一些錯誤ESI寄存器(在al值是正確的('a'),但在bl它不是(0)。我不知道我在做什麼錯。內嵌程序集 - 檢查單詞是否爲迴文

#include "stdafx.h" 
#include <iostream> 
#include <string> 
using namespace std; 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    char s[] = "arabara"; 
    int sizeofstring = 8; // size of s[] 
    int x = 0; 
    int y = 1; //flag when is_palindrome 
    __asm 
    { 
     lea edi, s 
     mov esi, edi 
     add esi, sizeofstring 
     dec esi //point to the last char 

     mov ecx, sizeofstring 
     cmp ecx, 1 
     je is_palindrome //single char is always a palindrome 

     shr ecx, 1 //divide by 2 

nextchar: 
     mov al, [edi] 
     mov bl, [esi] 
     cmp al, bl 
     jne stop 
     inc edi 
     dec esi 
     loop nextchar 

    is_palindrome: 
    mov eax, y 
    mov x, eax //change flag to 1 

stop: 
    } 

    cout << x << endl; //shoud print 1 when palindrome 
    system("pause"); 
    return 0; 
} 
+1

您最初將8添加到字符串的起始地址(_EDI_),並將該地址放入_ESI_中,即指向字符1你可以從ESI中減去1,這與[EDI + 7]相同,然後[ESI]([EDI + 7])中的字符就是nul(0)終止符。從_ESI_中減去2,而不是一個?替代方案將sizeofstring設置爲7而不是8(忽略長度中的nul終止符)。實際上,通過循環第一次將'a'和'\ 0'進行比較,當然它們是不同的。 –

+0

謝謝。它現在似乎在工作。 –

+0

你爲什麼使用內聯彙編做這件事?如果您正在嘗試學習彙編語言編程,那麼內聯彙編是一件非常糟糕的事情。只需配置Visual Studio以執行MASM,並且您可以繼續使用IDE和調試器。如果你不*試圖學習彙編,那麼用C++編寫代碼會更快更簡單。 –

回答

0

您將sizeofstring設置爲8,但您的字符串「arabara」長度爲7個字符。

+0

「阿拉伯數字」長度爲8個字符。不要忘記終止的空字符 – NathanOliver