指向数组的指针声明为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;
}
Run Code Online (Sandbox Code Playgroud)
将ouptut五个整数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.
}
Run Code Online (Sandbox Code Playgroud)
它产生:
error: cannot convert ‘int*’ to ‘int (*)[5]’
Run Code Online (Sandbox Code Playgroud)
您可以使用:
int (*a)[5] = new int[1][5];
Run Code Online (Sandbox Code Playgroud)
例:
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
0 10 20 30 40