1

We have the code:

int arr[3][4];

So arr is:

  1. An array of 3 elements, and every element is an array of 4 int.

  2. An array of 4 elements, and every element is an array of 3 int.

which one is right and why? How does it work with higher dimensional array? I suppose this is concerning operator precedence and associativity.

1
  • 4
    Perhaps what you are asking is about row-major order vs column-major order? Commented Dec 7, 2012 at 3:58

2 Answers 2

1

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[]

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

It is important to stick to row-major access behavior if you want to get good cache performance.
@Pubby Good point! I think that is information beyond the scope of this particular question and certainly would belong in a more in-depth discussion of C++ arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.