简体   繁体   中英

FInding starting addresses in memory with unions/structs in C

PROBLEM

My classmate and I are having trouble counting the memory and finding the start address for the last problem (see below). We are not sure how to count the bytes in the union to find the starting address of users[20].userinfo.donor.amount[1].
The answer, according to our professor, is 8009. Is this correct?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM