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]’
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With