我尝试将数组发送到函数,但我的程序卡住了
int main()
{
int n, i;
bool random;
cout << "number of elements in array:"; cin >> n;
cout << "use random values?"; cin >> random;
int* arr = new int[n]; //create int array with n size
init_array(random, n, arr); //fill array using function
for (i = 0; i <= n; i++) //display array
cout << " " << arr[i];
return 0;
}
此函数应使用随机数或键盘输入
填充数组void init_array(bool random, int n, int* arr)
{
int i;
if (random)
{
srand(time(0)); //initialize random;
for (i = 0; i < n; i++)
arr[i] = rand() % 100;
}
else
for (i = 0; i<n; i++)
cout << "arr[" << i << "]: "; cin >> arr[i];
}
有没有办法发送动态数组来运行?
答案 0 :(得分:2)
如果在for循环后不使用括号,则只将第一个语句用作循环:
else
for (i = 0; i<n; i++)
cout << "arr[" << i << "]: "; cin >> arr[i];
此循环将尝试打印“arr [#]”n
次,然后请求输入(将尝试将其放置在数组中最后一个元素(UB)之后的项目1中。
你想要的是这个:
else
{
for (i = 0; i<n; i++)
{
cout << "arr[" << i << "]: ";
cin >> arr[i];
}
}
您的输出也有问题:
for (i = 0; i < n; i++) // <= would attempt to print 1 more item than exists in the array
只是为了完整性,当您使用容器为您完成所有这些时,大多数问题都会消失:
int main()
{
int n = 0;
bool useRandom = false;
std::cout << "number of elements in array:";
std::cin >> n;
std::cout << "use random values?";
std::cin >> useRandom;
std::vector<int> arr(n);
init_array(useRandom, arr);
std::copy(arr.begin(), arr.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
void init_array(bool useRandom, std::vector<int>& vec)
{
::srand(time(0)); //initialize random;
int n = 0;
std::transform(vec.begin(), vec.end(), vec.begin(), [&](int i)
{
if (useRandom)
{
i = rand() % 100;
}
else
{
std::cout << "arr[" << n++ << "]: ";
std::cin >> i;
}
return i;
});
}
答案 1 :(得分:2)
由于上一个cin>>n
将else
部分修复为init_array
:
else
for (i = 0; i<n; i++)
{ //Notice braces
cout << "arr[" << i << "]: ";
cin >> arr[i];
}
还要修复:
for (i = 0; i < n; i++) //display array from index 0 to n-1
cout << " " << arr[i];