如何在C ++中返回指向数组的指针? [英] How can I return a pointer to an array in C++?
问题描述
这是我的简单代码 arrayfunc()应该在数组中存储一些数字,并返回该数组的指针 到将要打印数组内容的主要功能 我的代码有什么问题? 它仅返回指向数组第一个元素的指针 任何帮助将不胜感激. 预先感谢.
Here is my simple code arrayfunc() should store some numbers in an array, and return the pointer of this array to main function where the content of the array would be printed What is the problem with my code? It only returns the pointer to the first element of the array Any help will be appreciated. Thanks in advance.
#include <iostream>
using namespace std;
//The definition of the function should remain the same
int* arrayfunc()
{
int *array[10];
array[0] =new int;
array[1] =new int;
array[2] =new int;
array[3] =new int;
*array[0]=10;
*array[1]=11;
*array[2]=12;
*array[3]=13;
return *array;
}
int main()
{
for(int i=0;i<4;i++)
cout<<*(arrayfunc()+i)<<endl;
return 0;
}
推荐答案
(1)如果要返回它,则应为new
分配数组:int* array = new int[10];
[假设在这里,您需要int
s的数组而不是int*
的数组]
(2)返回指向数组中第一个元素的指针,请使用return array
而不是return *array
(3)您的数组是指针数组,而不是整数数组.
(1) You should allocate your array with new
if you want to return it: int* array = new int[10];
[assuming here you want array of int
s and not array of int*
's]
(2) to return the pointer to the first element in the array, use return array
and not return *array
(3) your array is array of pointers, and not array of ints.
这篇关于如何在C ++中返回指向数组的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!