Write a program that determines the offset address for an n -dimensional array (
ID: 3549173 • Letter: W
Question
Write a program that determines the offset address for an n-dimensional array (0 < n <= 4). Assume an element size of 2. The program should prompt the user to enter the following data:
The program should output the total size of the array and the address offset for the selected subscript combination. Allow the user to enter sets of subscripts until a -1 is entered. Terminate the program when a subscript of -1 is entered. For example:
Enter (R)ow or (C)olumn major order (R or C): R
Enter the number of dimensions for the array: 3
Enter the upper and lower bounds for subscript 1: 1 4
Enter the upper and lower bounds for subscript 2: 1 3
Enter the upper and lower bounds for subscript 3: 2 6
Enter a set of subscripts: 2 3 4
Offset to 2, 3, 4 is: 54
Array size is: 120
Enter a set of subscripts: -1 -1 -1
Successful termination of program
Explanation / Answer
int main() { char arr[5][7][6]; char (*p)[5][7][6] = &arr; /* Hint: &arr - is of type const pointer to an array of 5 two dimensional arrays of size [7][6] */ printf("%d ", (&arr + 1) - &arr); printf("%d ", (char *)(&arr + 1) - (char *)&arr); printf("%d ", (unsigned)(arr + 1) - (unsigned)arr); printf("%d ", (unsigned)(p + 1) - (unsigned)p); return 0; } int main() { char arr[5][7][6]; char (*p)[5][7][6] = &arr; /* Hint: &arr - is of type const pointer to an array of 5 two dimensional arrays of size [7][6] */ printf("%d ", (&arr + 1) - &arr); printf("%d ", (char *)(&arr + 1) - (char *)&arr); printf("%d ", (unsigned)(arr + 1) - (unsigned)arr); printf("%d ", (unsigned)(p + 1) - (unsigned)p); return 0; } Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.