What is the purpose of multidimensional arrays?

I have a few questions about multidimensional arrays. I understand how to allocate memory for them, but I do not understand why this is necessary (in addition to making things more readable).

The statement []for the array is overloaded, right? So why can’t you allocate one block of memory and gain access 1dArray[i*nInRow][offset],?

Is there any further increase in performance through the use of an array in several dimensions? Also, when the memory is dynamically allocated for the 2d array, are they stored in contiguous places or scattered across the heap? When data is requested, can I assume that everything is pulled out of memory as a block?

Most of the information I saw just explained the syntax. Any answers or suggested readings would be great.

+2
source share
3 answers

The [] operator for the array is overloaded, right? So, why can’t you allocate one block of memory and access it through 1dArray [i * nInRow] [offset]?

He can, and in fact I would recommend this in the general case.

Is there any further increase in performance through the use of an array in several dimensions?

Not really. Depending on your layout, you can optimize cache hits, but then the same is true for a flattened 1D array. The memory layout between them is (usually) exactly the same. The only difference is in the semantic type of the array and in the fact that now you need to implement the search for 2D elements yourself.

, 2d, ? , , ?

.

, 2D-. int** ptr = new int*[2], "-" , 2D-. . , "" . 2D- int (*ptr)[3] = new int[2][3];.

+2

-, . -, "", 99 * 99 * 99 * 99 *... * 99, , [ ] [] [J] []...

, , .

0

There are two types of 2d arrays:

1) the type in which all the memory is in one large block, and

2) the type in which each row (or each column) is adjacent, but the individual rows are scattered around, and you have an array of pointers pointing to each row.

Type # 2 has better performance if you want to do certain things, like replacing strings, because all you have to do is exchange two pointers.

0
source

All Articles