我正在尝试从函数中返回某个数组,该函数在调用时会将值分配给该数组
该函数应如下所示:
int arr[10];
int values[10] = {1,2,3,4,5,6,7,8,9};
for (int i =0; i<10; i++)
{
arr[i] = values[i];
}
如何将此代码转换为函数?使用命名空间std;
最佳答案
据我所知,您不应该从函数中返回数组……就像以前一样。
相反,我要做的是将数组的名称传递给函数,并使其以所需的任何方式处理内容。在您的情况下,您只是复制它们,这样就可以正常工作:
#include <iostream>
using namespace std;
void copy_array (const int [], int []); //function prototype
int main()
{
//Your arrays
int arr[10];
int values[10] = {1,2,3,4,5,6,7,8,9};
//Function call
copy_array(values, arr);
//Display contents of array
for(int i =0; i<10; i++){
cout << arr[i] << " " ;
}
return 0;
}
//Function definition
void copy_array (const int values[], int arr[]){
for (int i =0; i<10; i++){
arr[i] = values[i];
}
}
输出量1 2 3 4 5 6 7 8 9 0
另外,您的数组大小应该是一个常量整数变量。
关于c++ - 如何从函数返回具有多个值的数组? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64072751/