Returns a pointer to a new array

A pointer to an array is declared as Type (*p)[N];. For instance,

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;
}

prints five integers in a.

How to convert from new int[5]to type int (*p)[5].

For example, when I write a function that returns a pointer to a new array, the following code does not compile.

int (*f(int x))[5] {
    int *a = new int[5];
    return a; // Error: return value type does not match the function type.
}

He produces:

error: cannot convert β€˜int*’ to β€˜int (*)[5]’
+4
source share
6 answers

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;
}

Conclusion:

0
10
twenty
thirty
40
+5
source

You can clear your code with typedef, then it will be easier for you to see how to make it work:

#include <iostream>

typedef int (*P_array_of_5_ints)[5];

P_array_of_5_ints f() {
    int *a = new int[5];
    *a = 42;
    return (P_array_of_5_ints)a;
}

int main()
{
    P_array_of_5_ints p = f();
    std::cout << (*p)[0] << '\n';
}

(see it here on ideone.com )

+4
source

++, . vector. , !

std::vector<int> f(int x)
{
    std::vector<int> a(5);
    return a;
}
+1
#include <iostream>
using namespace std;

int (*f(int x))[5]
{
    int (*a)[5] = new int[1][5];
    return a; // Error: return value type does not match the function type.
}


int main(void)
{

 int a[5] = { 5, 4, 3, 2, 1 };
 int(*ptr_a)[5] = &a;
 for (int i = 0; i < 5; ++i)
 {
    cout << (*ptr_a)[i] << endl;
    cout << f(i) << endl;
 }
}
+1

++ 11 . std:: array c-style. , .

std::array<int,5> f()
{
    std::array<int,5> a;
    return a; 
}

, .

std::array<int,5>* f()
{
    std::array<int,5>* a = new std::array<int,5>;
    return a; 
}

, (, std:: unique_ptr), , .

typedef std::array<int,5> array_of_5_ints;
std::unique_ptr<array_of_5_ints> f()
{
    std::unique_ptr<array_of_5_ints> a = new std::array<int,5>;
    return a; 
}
+1

int (*f())[5] {
    int *a = new int[5];
    //code ...
    return (int (*)[5])a;
}
-2

Source: https://habr.com/ru/post/1547527/


All Articles