0

How exactly a 2d array is stored in memory?

Arrays are generally stored linearly in the memory. Since it stores the data continuously, how can the memory differentiate it as an array of array ?

15th Aug 2022, 10:59 AM
Levi
Levi - avatar
2 Réponses
0
For example, consider the following 2D array of integers: int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; This array would be stored in memory as: 1 2 3 4 5 6 7 8 9 10 11 12 To access an element of the array, the program would need to compute the memory address of that element using the row and column indices. The formula for computing the memory address of an element in a 2D array is: address = base_address + (row_index * number_of_columns + column_index) * sizeof(element_type) where base_address is the memory address of the first element of the array, row_index and column_index are the indices of the element being accessed, and element_type is the type of the elements in the array (e.g. int, float, etc.). This is called row-major order method. Read more https://www.google.com/search?q=row-major+order&sourceid=chrome-mobile&ie=UTF-8 Most programming languages that support multidimensional arrays, such as C, C++, and Java, store the arrays in row-major order.
24th Dec 2022, 8:53 AM
Calviղ
Calviղ - avatar