0

With C++11, we can use

auto carrots{new double[rows][4]}

if we want to allocate dynamic two dimension array. Here I see another way to explicitly declare the pointer like

double (*carrots)[4]{new double[rows][4]} 

According to my understanding, double (*carrots)[4] is a pointer to an array of double[4]. I think there should be a mismatch between this and new double[rows][4]. Because I think double[rows][4] represents an array of size rows instead of array of size 4.

As we know the lay out of c++ two dimension array should like this

int test[3][2] {{0,1},{2,3},{4,5}}

is exactly the same as

int test[6]{0,1,2,3,4,5}
Sean
  • 901
  • 2
  • 11
  • 30
  • Why do you think there should be a mismatch? – doug Jan 25 '21 at 02:30
  • @doug Please check the edited version. Thank you. – Sean Jan 25 '21 at 02:37
  • The `carrots` initializing expressions decay into `double(*)[4]` OTOH, your two `test` examples do not decay and are 2D arrays. They (`test`)are different types even though the memory layout is the same. Examine them with a debugger or to see how the types differ. Is this not what you expected? – doug Jan 25 '21 at 02:56
  • *"`double (*carrots)[4]` is a pointer to an array of double[4]"* & *"`double[rows][4]` represents an array of size rows instead of array of size 4."* -- yes, so why is this a mismatch? In the former quote, you describe the elements of the array and ignore the size, while in the latter quote, you describe the size of the array and ignore the elements. Why can an array of size rows not have elements whose type is `double[4]`? – JaMiT Jan 25 '21 at 03:01
  • The type of `new double[rows][4]` is a pointer to an array of 4 doubles. It is not a pointer to an array of arrays. – doug Jan 25 '21 at 03:15
  • Take a look at this: https://stackoverflow.com/questions/19467909/will-the-new-expression-ever-return-a-pointer-to-an-array `new double[rows][4]` returns a pointer to the first element of an array of arrays but it's type is a pointer to an array. Yeah, can be confusing. – doug Jan 25 '21 at 03:37
  • What stops you from using `std::vector`? I mean its easy and dynamic and manages a lot of things for you... – D-RAJ Jan 25 '21 at 06:36

0 Answers0