Consider the following function header:
void do_something_crazy(char *ascii_art, const size_t num_rows, const size_t num_cols) { /* ... body omitted ... */ }
where the array ascii_art is assumed to be a one-dimensional view of a two-dimensional array with num_rows rows and num_cols columns.
If the function is called in the following way:
do_something_crazy(a, 48, 96);
Which of the following expressions when used within the function accesses the element in the 8th column of the 17th row of the array? (click all that apply)
ascii_art[1543]
ascii_art[17][8]
ascii_art[1640]
Let us take an example of 2 dimensional array :
A[3][3] = {{1,2,3},{4,5,6},{7,8,9}}
Example1. If we want to store the elements in to 1D array row by row, then elements in 1D array is stored as below:
B[9] = {1,2,3,4,5,6,7,8,9}
m= Total num of rows
n= Total no of columns
Now we can access the 2nd row (r) 3 rd column(c) value (6) of A is stored in B with below position index
= B[(r-1)*n+c-1]
= B[(1*3)+3-1]
= B[(3+3-1]
= B[5] = 6 (Index of array starts from '0')
Example2. If we want to store the elements in to 1D array column by column, then elements in 1D array is stored as below:
B[9] = {1,4,7,2,5,8,3,6,9}
m= Total num of rows
n= Total no of columns
Now we can access the 2nd row (r) 3 rd column(c) value (6) of A is stored in B with below position index
= B[(c-1)*m+r-1]
= B[(3-1)*3+2-1]
= B[(2*3+2-1]
= B[6+2-1]
= B[7] = 6 (Index of array starts from '0')
1) Similarly the above question has
Total no of rows, m = 48
Total no of columns, n = 96
r = 17
c = 8
a) Row By Row
= ascii_art[(r-1)*n+c-1]
= ascii_art[(17-1)*96+8-1]
= ascii_art[16*96 + 8 - 1]
= ascii_art[ 1536+8-1]
= ascii_art[1543]
a) Column By Column
= ascii_art[(c-1)*m+r-1]
= ascii_art[(8-1)*48+17-1]
= ascii_art[7*48 + 17 - 1]
= ascii_art[ 336+17-1]
= ascii_art[352]
The only two possible options are ascii_art[1543] and ascii_art[352] depending on your way of forming 1D array from from 2D array.
2) ascii_art[17][8] is not valid because the pointer declared can hold 1D array only and if we try to acces it as 2D array, you will get error.
3) ascii_art[1640] is not valid because this position is not formed for given row and column either in Row by Row arrangement or Column by Column arrangement.
If you have any queries regarding this answer, please reach out through the comment section.
Get Answers For Free
Most questions answered within 1 hours.