Hey js19,
My program is suppose to fill in a structure of a book (author, title, subject, year) store it in a pointer, use assembly to access the structure and compare the year.
I'm not sure about how your class deals with this stuff, but NASM does actually support structures.
In my C code:
struct book {
char author[20 + 1];
char title[32 + 1];
char subject[10 + 1];
unsigned int year;
};
Awesome! You've got a C structure. Let's try to turn that into a NASM structure. We do this with the
STRUC/
ENDSTRUC directives.
STRUC book
.author: RESB (20+1) ; reserve 20+1 bytes for book.author
.title: RESB (32+1) ; reserve 32+1 bytes for book.title
.subject: RESB (10+1) ; reserve 10+1 bytes for book.subject
.year: RESD 1 ; reserve 1 32-bit unsigned integer for book.year
ENDSTRUC
In my assembly code: mov ebx, [book1]
mov ecx, [book2]
holds the book pointers.
How do I go about accessing book1->year in assembly?
You would use the notation
[base_ref + structure.element] to access the elements of your structure. For your example, you've dereferenced the book1 pointer by assigning it's address to ebx (and the same for ecx). Remember from your C classes that the '->' operator is a shorthand semantic; for example
book1->year is a shorthand for
(*book1).year. In the latter form we can clearly see that we are dereferencing a pointer and treating it as a regular structure. This is exactly how we do it in assembly.
mov ebx, [book1] ; ebx = book1
mov ebx, [ebx] ; ebx = *ebx
mov edi, [ebx + book.year] ; edi = ebx.year
When trying to translate ideas from C to assembly, it's usually best to avoid the syntactic sugars and stick to the longer forms because they translate better. This also includes things like using
<bool-expr>?<true-clause>:<false-clause> instead of the longer
if (<bool-expr>) <true-clause> else <false-clause> form, these can sometimes make translation a little harder.
If you're teacher wants you to use the numbers directly, you could always count the number of bytes from the beginning of the
STRUC to the .year label and use that in place of
book.year, in your case it would be:
book.year = (20+1) + (32+1) + (10+1) -> 21 + 33 + 11 -> 65So the above code would change to:
mov ebx, [book1] ; ebx = book1
mov ebx, [ebx] ; ebx = *ebx
mov edi, [ebx + 65] ; edi = ebx.year