コードがあります:
int arr[3][4];
そうarr
です:
3つの要素の配列であり、すべての要素は4つのintの配列です。
4つの要素の配列であり、すべての要素は3つのintの配列です。
どちらが正しいのか、そしてその理由は?高次元配列ではどのように機能しますか?これは、演算子の優先順位と結合性に関するものだと思います。
コードがあります:
int arr[3][4];
そうarr
です:
3つの要素の配列であり、すべての要素は4つのintの配列です。
4つの要素の配列であり、すべての要素は3つのintの配列です。
どちらが正しいのか、そしてその理由は?高次元配列ではどのように機能しますか?これは、演算子の優先順位と結合性に関するものだと思います。
Your first interpretation is correct.
Such declarations are best parsed using the Right Left rule, which you can read here and here
$8.3.4 from the C++ draft Standard: ...
Example: consider int x[3][5]; Here x is a 3 × 5 array of integers.
...
Note: It follows from all this that arrays in C++ are stored row-wise (last subscript varies fastest) and that the first subscript in the declaration helps determine the amount of storage consumed by an array but plays no other part in subscript calculations. —end note ]
Note C++ does not have operator[][]. It has only operator[]
I find it easiest to think of the "rows" and "columns" in a multidimensional array rather than trying to get my mind around "arrays of arrays". This has the convenient property that I decide which index is the rows and which is the columns. In other words, I can think of int arr[3][4];
as a 2D array either with 3 rows and 4 columns or with 4 rows and 3 columns. As long as my code is consistent with my mental view of the array, all will work out fine. However, if half-way through a program I switch views, things will start breaking.
With that said, usually I prefer to think of this example as 3 rows and 4 columns since this is similar to the mathematical notation in linear algebra where rows are listed first.