2D array quiestion.

Hey guys, I'm trying to understand 2D arrays a little bit more in depth. Please correct me if I am mistaken about something.

Lets say I have array<array<int, 3>, 2> = {1,2,3,4,5,6};

 
  array<array<int, 3>, 2>array1 = {1,2,3,4,5,6};


I know that array1 is a pointer to the first element in the array, and that a pointer points to a memory address. In a 1 dimensional array, the array has a contiguous memory, what happens with a 2D array? I know each element in the array can't hold a separate array in memory, as each array would need its own contiguous memory, which would make the 'outer array' uncontiguous.

I apologize for the poor wording.
I know that array1 is a pointer to the first element in the array

This isn't quite true.

Note that conventionally when people mention "arrays" they mean C-style arrays -- e.g., int array[] { ... };. std::array is usually qualified as a "C++" array, or called a std::array.

With that being said, you expressed two incompatible simplifications:
1. std::array is not a (C-style) array: C-style arrays are built into the language; std::array is a library component.
2. Neither std::arrays nor C-style arrays are pointers, although claiming the latter is a common error because there is an implicit array-to-pointer conversion and some additional confusing syntax. However, there is no conversion between std::array<T, N> and T*, although you can get a pointer to the first element via the member function data().

Try not to consider even C-style arrays as pointers or multidimensional arrays will never make any sense.

I know each element in the array can't hold a separate array in memory, as each array would need its own contiguous memory, which would make the 'outer array' uncontiguous.

Nope.
std::array is an aggregate type. It is exactly contiguous and exactly the same size as C-style array of the same size and bounds. There is no extra indirection when accessing a std::array -- IOW, it doesn't have a pointer to dynamic memory somewhere like std::vector does. The array is stored inside the object itself.
Last edited on
Topic archived. No new replies allowed.