返回一个指向新数组的指针

Return a pointer to a newed array

本文关键字:数组 指针 新数组 一个 返回      更新时间:2023-10-16

指向数组的指针声明为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;
}
输出:

<>之前01020.30.40

您可以使用typedef来清理代码,然后更容易看到如何使其工作:

#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';
}

你已经标记了c++,所以请不要这样做。使用vector代替。它清理了整个语法确保您不会泄漏内存!

std::vector<int> f(int x)
{
    std::vector<int> a(5);
    return a;
}
#include <iostream>
using namespace std;
int (*f(int x))[5]
{
    int (*a)[5] = new int[1][5];
    return a; // Error: return value type does not match the function type.
}

int main(void)
{
 int a[5] = { 5, 4, 3, 2, 1 };
 int(*ptr_a)[5] = &a;
 for (int i = 0; i < 5; ++i)
 {
    cout << (*ptr_a)[i] << endl;
    cout << f(i) << endl;
 }
}

c++ 11有更好的方法来处理固定大小的数组。我建议使用std::array而不是c风格的数组。一个现代的编译器应该发出和指针版本一样高效的代码。

std::array<int,5> f()
{
    std::array<int,5> a;
    return a; 
}

如果你真的想乱用指针,用下面的

std::array<int,5>* f()
{
    std::array<int,5>* a = new std::array<int,5>;
    return a; 
}

我还建议不要使用原始指针,而是使用智能指针。Std::unique_ptr),以防止由于忘记删除数组而导致内存泄漏。

typedef std::array<int,5> array_of_5_ints;
std::unique_ptr<array_of_5_ints> f()
{
    std::unique_ptr<array_of_5_ints> a = new std::array<int,5>;
    return a; 
}

将函数更改为

int (*f())[5] {
    int *a = new int[5];
    //code ...
    return (int (*)[5])a;
}