返回一个指向新数组的指针
Return a pointer to a newed array
指向数组的指针声明为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;
}
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”