In: Computer Science
Arrays in C, including Multi Dimensional Arrays
- Which is more space efficient - a 2 dimensional
array (int array[10][10]) or an array of int pointers where each
element of the array points to an int array (int *array[10],
array[0] = int sub_array[10])? Why?
- Given the declaration int array[10][10], using pointer arithematic and the address &array[0][0], how do you retrieve the value of the element at array[5][3]?
- Given the declaration int array[10][10][10], using pointer arithematic and the address &array[0][0][0], how do you retrieve the value of the element at array[5][3][1]?
- Given the following code, what does the print
statement output?
int foo[2][2][3] = {
{ {1,2,3}, {4,5,6} },
{ {7,8,9}, {10,11,12} }
};
printf("%d", foo[0][1][2]);
1)
array[10][10] requires 100 continuous memory locations to store them. But array of pointers requires just 100 memory locations. It need not to be continuous,
So array of pointers is efficient if memory doesn't have 100 continuous memory locations but 100 locations available in sparsed manner.
2)
array[5][3] = 5 is row, 3 is column.
i*rowSize+k =
i is the required row number, 5 in our case
rowSize is 10 in our case
k is the required column which is 3.
Each element occupies memory of its type. In our case it is int.
address(array[0][0]) + (5 * 10 + 3) * size(int)
base address + (each row contains 10 elements, we need 53rd element address of integer type)
4)
foo[0] is { {1,2,3}, {4,5,6} } //It contains two elements indexed 0
foo[0][1] is {4,5,6} // So index 1 is second set of elements
foo[0][1][2] is 6 // Second element in the above set is 6 as it is 0 indexed
so it prints 6
3)
total number of rows * total number of columns * required row number + total number of third index * required column number + 1 will give the required element from the base addres
*(&array[0][0][0] + 10 * 10 * 5 + 10 * 3 + 1) as in answer 2