getting the address value without word alignment?
I have this question:
suppose that the size of "char" is one byte and the size of "int" and "float" is 4 bytes.
struct Employee
{
int age;
char sex;
char name[25];
float info[3][10];
};
Employee x;
what is the address of "x.info[2][5]" without word alignment, supposing that t开发者_如何学JAVAhe adress of "x" is 1000 ?
note: this is not a homework but i had an exam and i answered this wronge. I really wold like to know the right answer.
thanx
I am not sure about other languages, but in C and C++ this is how a 2-D array will be stored in the memory:
Your float info[3][10]
has 3*10 = 30 float
s in the memory.
If the first memory location of your 2-D array is 1000 i.e &info[0][0]
then your &info[2][5]
will be 1000 + sizeof(float) * (2*10 + 5) = 1100 i.e first_memory_location + sizeof(data_type) * (row_no * total_no_columns + column_no).
Have a look at this link to understand the concept better
EDIT: The same calculation holds good for 2-D arrays inside a struct.
In your case, there is an int, a char and a char array of size 25. So your &info[0][0]
= 1029
First_memory_location + sizeof(float) * ( row_no * total_no_columns + column_no)
1029 + 4 *(2*10 + 5) = 1129
[I will suppose that X in your question is noise from an alien spacecraft]
Address &info[2][5] is then info[2]+5 = (char*)info+ sizeof(float)*2*10+5*sizeof(float) == (char*) info + 100
sizeof(float)==4
I think in this case you need to add the memory space of all variables together in order, not just the address space of x.
So if the address of x is 1000, the address you want would be at
1000
+sizeof(int) // age
+sizeof(char) // sex
+(sizeof(char)*25) // name
+(sizeof(float)*2*10) + sizeof(float)*5 // info[2][5]
Assuming usual sizes, that would be 1000 + 8 + 1 + 25 + 120 = 1154
精彩评论