指向数组的指针声明为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]
为type 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句