In: Computer Science
Consider the following declaration:
typedef struct{
int A;
char B[10];
float C;
char D;
}rectype;
typedef rectype matrix[121][4][5];
matrix A1;
Compute the address of element A1[120][3][3] given the base address
at 2000.
Solution:
step1: The basics are
To determine the ith element of a Three-dimension array:A[i][j][k]=BA+[(i)*(UB2)*(UB3)+(j)*(UB3)+(k)]* datasize
Where
UB3–upper bound of the 3rd dimension
UB2–upper bound of the 2nddimension
BA is base or starting address
datasize–element size in bytes
Step2:
But if we see the size of rectype is 24 bytes because of sizeof(structure) is arranged in the form of words for processor. For a 32 bit processor it is 4bytes each word and for 64 bit processor it is 8bytes each word.
int size=4 bytes, char size=1 byte, float size=4 bytes
Hence size(rectype)=firstword for integer+second,third,fourth for char B+fifth for float + sixth for char
=
1 2 3 4 5 6
int A | char B | char B | char B | float C | char D |
=first word is occupied by integer+second is occupied by 4 char+third is occupied by 4 char+fourth is occupied by 2 char(remaining 2 bytes goes in fragmentation)+fifth word by float+sixth by char (remaining 3 bytes is wasted)
=4+4+4+4+4+4=24 bytes
i=120, j=k=3 UB2=4 UB3=5 BA=2000 datasize=24 bytes
A1[120][3][3]=BA+[(i)*(UB2)*(UB3)+(j)*(UB3)+(k)]* datasize
=2000+[120*4*5+3*5+3]*24=60032
conclusion: Hence the address of element A1[120][3][3] if the base address 2000 is 60032.