Return a pointer to a newed array

c++, pointers

Solution

You can use:

int (*a)[5] = new int[1][5];

Example:

#include <iostream>

int main()
{
   int (*a)[5] = new int[1][5];
   for ( int i = 0; i < 5; ++i )
   {
      (*a)[i] = 10*i;
      std::cout << (*a)[i] << std::endl;
   }
   delete [] a;
}

Output:

0
10
20
30
40

Problem

A pointer to an array is declared as `Type (*p)[N];` . For example, ``` int a[5] = { 1, 2, 3, 4, 5 }; int(*ptr_a)[5] = &a; for (int i = 0; i < 5; ++i){ cout << (*ptr_a)[i] << endl; } ``` would ouptut the five integers in `a`. How to convert from `new int[5]` to the type `int (*p)[5]`. For example, when I write a function that returns a pointer to a new array, the following code doesn't compile. ``` int (*f(int x))[5] { int *a = new int[5]; return a; // Error: return value type does not match the function type. } ``` It produces: ``` error: cannot convert ‘int*’ to ‘int (*)[5]’ ```

Original source