问题
我的同学和我无法计算内存并找到最后一个问题的起始地址(见下文)。我们不确定如何计算联合中的字节来查找用户的起始地址[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
答案 0 :(得分:0)
通过下面的测试程序确认@paddy和@jxh评论 8090 是正确的答案。
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