我正在尝试创建一个无论数组大小都能工作的函数,我被困住了,无法弄明白。我知道这个当前的代码不起作用,因为我将10个数据输入到只存储5个数组的内存中。寻找一个简单的解决方案并向正确的方向推进。提前谢谢。
#include <iostream>
#include <conio.h>
using namespace std;
void getInput(int []);
int main()
{
int numbers[5],
nums[10],
i;
getInput(numbers);
cout << "\nThe numbers are:\t";
for(i = 0; i < 5; i++)
cout << numbers[i] << " ";
cout << endl;
getInput(nums);
cout << "\nThe numbers are:\t";
for(i = 0; i < 10; i++)
cout << nums[i] << " ";
cout << endl;
_getch();
return 0;
}
void getInput(int num[])
{
int i;
for (i = 0; i < 10; i++)
{
cout << "Enter number #" << i+1 << ": ";
cin >> num[i];
}
}
答案 0 :(得分:0)
您需要告诉函数要处理多少个数字:
#include <iostream>
using namespace std;
void getInput(int [], int);
int main()
{
int numbers[5],
nums[10],
i;
getInput(numbers, 5);
cout << "\nThe numbers are:\t";
for(i = 0; i < 5; i++)
cout << numbers[i] << " ";
cout << endl;
getInput(nums, 10);
cout << "\nThe numbers are:\t";
for(i = 0; i < 10; i++)
cout << nums[i] << " ";
cout << endl;
cin.get();
return 0;
}
void getInput(int num[], int maxnums)
{
for (int i = 0; i < maxnums; ++i)
{
cout << "Enter number #" << i+1 << ": ";
cin >> num[i];
}
}
如果你只传入静态数组(这对于动态数组或指针不起作用),你可以通过使函数使用模板参数自动传递数组大小,让编译器推导出每个数组的值。传递数组:
#include <iostream>
using namespace std;
template <const size_t n>
void getInput(int (&nums)[n])
{
for (int i = 0; i < n; ++i)
{
cout << "Enter number #" << i+1 << ": ";
cin >> num[i];
}
}
int main()
{
int numbers[5],
nums[10],
i;
getInput(numbers);
cout << "\nThe numbers are:\t";
for(i = 0; i < 5; i++)
cout << numbers[i] << " ";
cout << endl;
getInput(nums);
cout << "\nThe numbers are:\t";
for(i = 0; i < 10; i++)
cout << nums[i] << " ";
cout << endl;
cin.get();
return 0;
}