Kam*_*ron 5 c++ memory assembly mixed-mode
这是我的编程任务.我需要使用8086编程语言编写的方法找出整数数组中最大的.这是我的尝试:
#include <iostream.h>
#include <conio.h>
int returnLargest(int a[])
{
int max;
asm mov si,offset a
for(int i=0;i<6;i++) //Assuming six numbers in the array...Can be set to a variable 'n' later
{
asm mov ax,[si]
asm mov max,ax
asm inc si
cout<<max<<"\n"; //Just to see what is there in the memory location
}
asm mov si,offset a
asm mov cx,0000h
asm mov dx, [si]
asm mov cx,06h
skip: asm mov si,offset a
asm mov bx,[si]
asm mov max,bx
asm inc si
abc: asm mov bx,max
asm cmp [si],bx
asm jl ok
asm mov bx,[si]
asm mov max,bx
ok: asm loop abc
asm mov ax,max
return max;
}
void main()
{
clrscr();
int n;
int a[]={1,2,3,4,5,6};
n=returnLargest(a);
cout<<n; //Prints the largest
getch();
}
Run Code Online (Sandbox Code Playgroud)
预期的答案是
1 2 3 4 5 6 6.但我得到的是: 
在这里,我坐下来思考......难道它不是数据的索引i实际存储在内存中的值吗?因为至少我们被教导如果[i]是12(比如说),那么第i个记忆位置就会在其中写入数字12.
或者,如果值未存储在内存位置,如何写入内存位置以完成所需任务?
我还要求大家在网/平装上链接一些材料,以便了解这些概念.
编辑:
装配中的相同代码工作得很好......
data segment
a db 01h,02h,03h,04h,05h,06h,'$'
max db ?
data ends
code segment
start:
assume cs:code,ds:data
mov ax,data
mov ds,ax
mov si,offset a
mov cx,0000h
back: mov dl,byte ptr [si]
cmp dl,'$'
je skip
inc cx
inc si
jmp back
skip: mov si,offset a
mov bl,byte ptr[si]
mov max,bl
inc si
abc: mov bl,max
cmp [si],bl
jl ok
mov bl,[si]
mov max,bl
ok: loop abc
mov al,max
int 03h
code ends
end start
Run Code Online (Sandbox Code Playgroud)
mov si,offset a 是不正确的.当你声明一个函数参数时int a[],该函数实际上会收到一个指针.由于您需要指针值(a)而不是其地址(&a在C中,offset a在程序集中),请使用mov si, a.
此外,inc si看起来不正确-你需要增加si通过sizeof(int)对每个元素.
编辑:
您正在将C++代码(for循环cout)与程序集混合使用.C++代码可能使用相同的寄存器,这会导致冲突.你应该避免这样做.
您还需要根据所使用的调用约定找出允许您的函数更改的寄存器.如果您使用任何不允许更改的寄存器,则需要push在开头和pop结尾处使用它们.