算术和强制转换指针和结构

arithmetic and cast pointers and structures

我有一个结构数组,定义如下。

typedef struct
{
    _id customer_id;          // unsigned int (4 bytes)
    char customer_name [40];
    char customer_surname [40];
    char customer_vat [40];
    char customer_add [60];
    char customer_email [60];
    char customer_land_phone [22];
    char customer_mob_phone [22];
    time_t customer_creation_date;    // long int (8 bytes)
} _Customer_Struct;

和一组结构...

_Customer_Struct customers [x];   // x is irrelevant

以及我的结构数组成员的偏移量数组...

const size_t offset [9] =
{
    (&customers[0].customer_id - (_id *) customers) / sizeof (_id), // stores 0
    (&customers[0].customer_name[0] - (char *) customers) / sizeof (char), // stores 4
    (&customers[0].customer_surname[0] - (char *) customers) / sizeof (char), // 44
    (&customers[0].customer_vat[0] - (char *) customers) / sizeof (char), // 84
    (&customers[0].customer_add[0] - (char *) customers) / sizeof (char), // 124
    (&customers[0].customer_email[0] - (char *) customers) / sizeof (char), // 184
    (&customers[0].customer_land_phone[0] - (char *) customers) / sizeof (char), // 244
    (&customers[0].customer_mob_phone[0] - (char *) customers) / sizeof (char), // 266
    (&customers[0].customer_creation_date - (time_t *) customers) / sizeof (time_t) // 4 what...?
};

每一行旁边都有一个注释,其中包含为每个表达式存储的值。现在,看看最后一行 (&customers[0].customer_creation_date - (time_t *) customers) / sizeof (time_t)。如果我理解,这应该将 customers (数组)的基地址转换为 time_t,这等于 long int,从 &customers[0].customer_creation_date 中减去其地址的值,得到形式为 n*[=16= 的部分结果],最后将它除以 (time_t) 的字节大小,产生相应的字节偏移量。基本上和前八行一样.

问题 1:为什么这个表达式产生 4 而不是 288?

问题 2:为什么我将它转换为 char 而不是它?

(char *)&customers[0].customer_creation_date - (char *) customers) / sizeof (char)实际产生288.

您正在进行指针数学运算来计算偏移量,这是有效的,但请记住,指针数学运算旨在生成一个整数,该整数可用作指针所指向类型数组的索引。

所以:

(&customers[0].customer_creation_date - (time_t *) customers)

正在计算假设的 'j' 是什么:

((time_t *)&customers)[j] == &customers.customer_creation_date

并且当您将指针转换为 (char *) 时,指针数学是以字符形式完成的,这就是您的意思。这同样适用于 customer_id,除了因为它是第一个,所以它的偏移量无论如何都是零。