1

问题

我和我的同学在计算内存和找到最后一个问题的起始地址时遇到了麻烦(见下文)。我们不确定如何计算联合中的字节数以找到 users[20].userinfo.donor.amount[1] 的起始地址。
根据我们教授的说法,答案是 8009。这是正确的吗?

Assume that a char = 1 byte, int = 4 bytes, double = 8 bytes, and pointers are 4 bytes.

struct address {
   char street[100];
   char city[20];
   char state[2];
   char zip[10];
};
struct date {
   int month;
   int day;
   int year;
};
struct user {
   char login[20];
   char fullname[100];
   char password[30];
   struct address physical_address;
   struct date birthday;
   int user_type;
   union {
      struct {
         double salary;
     char *clearance;
      } admin;
      struct {
         date donationdate[2];
         double amount[2];
      } donor;
      struct {
         double wage;
     date datehired;
      } worker;
   } userinfo;
};

struct users[200];

If the users begins at a memory address 1000, what are the starting addresses (in bytes) of each of the following:
a) users[10]
b) users[15].physical_address.street
c) users[20].birthday.year
d) users[20].userinfo.donor.amount[1]

Solutions:
a) 4380
b) 6220
c) 8050
d) 8009
4

1 回答 1

0

Confirmed @paddy and @jxh comments via a test program below.
8090 is the correct answer.

struct user *users = (struct user *) 1000;
// used __attribute__((packed)) on each structure
int main() {
  printf("size %zu %zu %zu %zu\n", sizeof(char), sizeof(int), sizeof(double), sizeof(void *));
  printf("%zu\n", (size_t)&users[10]                         );
  printf("%zu\n", (size_t)&users[15].physical_address.street );
  printf("%zu\n", (size_t)&users[20].birthday.year           );
  printf("%zu\n", (size_t)&users[20].userinfo.donor.amount[1]);
  return 0;
}
//size 1 4 8 4
//4380
//6220
//8050
//8090
于 2013-08-15T04:12:45.130 回答