Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a pointer to a newed array

Tags:

c++

pointers

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]’
like image 268
Peng Zhang Avatar asked Dec 25 '22 07:12

Peng Zhang


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

Output:

0
10
20
30
40
like image 167
R Sahu Avatar answered Jan 06 '23 21:01

R Sahu


You can clean up your code using a typedef, then it's easier to see how to get it working:

#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 running here at ideone.com)

like image 31
Tony Delroy Avatar answered Jan 06 '23 20:01

Tony Delroy