#include <stdio.h>
#include <stdlib.h>
typedef struct item {
int low; int high; char label[16];
} Item;
typedef struct item_coll {
size_t length; Item *items[];
} ItemColl;
extern char *find_first_in_range(ItemColl *ic, int rlow, int rhigh);
/*
char *find_first_in_range(ItemColl *ic, int rlow, int rhigh) {
for (size_t i = 0; i < ic->length; i++)
if (ic->items[i]->low >= rlow && ic->items[i]->high <= rhigh)
return &ic->items[i]->label[0];
return NULL;
}
* */
int main() {
struct item fruits[] = {
{10, 20, "Apple"},
{12, 14, "Pear"},
{ 8, 12, "Banana"},
{ 2, 4, "Grape"},
{15, 35, "Watermelon"}
};
struct item_coll *basket = malloc (sizeof *basket + 5 * sizeof *basket->items);
basket->length = 5;
for (size_t i = 0; i < 5; i++)
basket->items[i] = &fruits[i];
char *label = find_first_in_range (basket, 12, 15);
printf ("%s\n", label);
free (basket);
return 0;
}
我有这个C程序,目标是在汇编中创建
find_first_in_range
函数。现在,我只是想去10
中的Apple
,但是在%rax
中给了我一个奇怪的值。这是我在汇编中所做的:
.globl find_first_in_range
# *ic is passed in %rdi
# rlow is passed in %rsi
# rhigh is passed in %rdx
find_first_in_range:
mov %rdi, %rax
%rsi
保持12
,而%rdx
保持15
,这是我在find_first_in_range (basket, 12, 15);
中传递的左右限制,但%rax
不应保持10
吗?从fruits[]
的第一个元素开始。我还有一个问题是如何访问例如
basket
的长度?这是5
。 最佳答案
ic
中的是%rdi
本身:ItemColl
的指针。因此,作为该结构中的第一个元素ic->length
(在mov
之后)只是(%rax)
(大概8个字节长)。