我试图将数组发送给函数,但我的程序卡住了
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];
}
有什么方法可以发送动态数组来运行吗?
最佳答案
如果在 for 循环后不使用方括号,则只有第一个语句用作循环:
else
for (i = 0; i<n; i++)
cout << "arr[" << i << "]: "; cin >> arr[i];
此循环将尝试打印“arr[#]”n
次,然后请求输入(这将尝试放置在数组中最后一个元素之后的第 1 项中( UB)。
你要的是这个:
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;
});
}
关于c++ - 在 C++ 中发送指向函数的动态指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19893707/