我正在自学成书。当前的任务是,我必须通过一个不返回任何内容的函数(我假设一个void函数)放置一个带有两个下标的数组,然后递归打印每个元素。
#include <iostream>
#include <array>
#include <iomanip>
#include <string>
#include <cstddef>
using namespace std;
void printArray (int source, int a, int b){
if (a < b){
cout << source[a] << " ";
printArray(source, a + 1, b);
}
}
int main (){
const array<int, 10> theSource = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int al = 0;
int bl = theSource.size();
printArray(theSource, al, bl);
}
当我尝试执行此操作时,出现两个错误。
11|error: invalid types 'int[int]' for array subscript|
22|error: cannot convert 'const std::array<int, 10u>' to 'int' for argument '1' to 'void printArray(int, int, int)'|
所以我尝试将void更改为...
void printArray (int source[], int a, int b)
并且...
void printArray (int *source, int a, int b){
但是仍然出现错误...
22|error: cannot convert 'const std::array<int, 10u>' to 'int' for argument '1' to 'void printArray(int, int, int)'|
有没有其他方法可以通过函数放置数组?
任务是...
最佳答案
将签名更改为:
void printArray (const array<int, 10> &source, int a, int b)
这就是编译器想要的! :)
关于c++ - 将数组传递给void函数,然后递归打印元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41152026/