指向数组的指针声明为 Type (*p)[N];
。例如,
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;
}
会输出 a
中的五个整数。
如何将 new int[5]
转换为 int (*p)[5]
类型。
例如,当我编写一个返回指向新数组的指针的函数时,以下代码无法编译。
int (*f(int x))[5] {
int *a = new int[5];
return a; // Error: return value type does not match the function type.
}
它产生:
error: cannot convert ‘int*’ to ‘int (*)[5]’
最佳答案
您可以使用:
int (*a)[5] = new int[1][5];
例子:
#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;
}
输出:
0 10 20 30 40
关于c++ - 返回指向新数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623694/