c++ - 返回指向新数组的指针

标签 c++ pointers

指向数组的指针声明为 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/

相关文章:

c++ - 如何正确使用vector<uint8_t>.data()?

c++ - 我们应该使用什么作为 std::strcpy 的第二个参数?

C `Abort trap: 6` 仅在某些条件下

c++打包和解包参数包以在没有STL的情况下调用匹配的函数指针

c++ - C#WPF和C++/CLI和C++在C++/CLI中添加外部库错误

c++ - 创建一个自定义整数,强制始终在指定范围内;如何克服整数溢出?

c - 什么是 C 中指向对象类型的指针?

c - 传递函数指针

c++ - 将(行)从二维数组复制到一维数组

c++ - 模板实参作为模板参数传给另一个模板时,为什么推导不出来?