[英]Passing array as an argument from one function to another in C++?
I have a program where I want to pass an array - in this case k[arrsize]
, which is a parameter of the funciton fillArray()
to the other function create_file()
(the same array, filled with the random numbers). 我有一个要在其中传递数组的程序-在本例中为
k[arrsize]
,它是funciton fillArray()
到另一个函数create_file()
(同一数组,用随机数填充)。 However, I cannot pass the same array and I would like to ask how can this be done? 但是,我不能传递相同的数组,我想问一下如何做到这一点?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <time.h>
#include <stdlib.h>
using namespace std;
const int arrsize = 20;
//int a[arrsize];
fstream p;
void fillArray(int k[arrsize])
{
srand((unsigned)time(NULL));
for (int i = 0; i<20; i++)
{
if (i % 2 == 0)
{
k[i] = -(rand() % 100);
}
else
{
k[i] = (rand() % 100);
}
}
}
void create_file(int k[arrsize])
{
p.open("danni.dat", ios::out);
for (int i = 0; i<20; i++)
{
p << k[i] << endl;
}
p.close();
}
int main() {
fillArray(k);
create_file(k);
return 0;
}
You simply forget to define an array: 您只是忘了定义一个数组:
int main() {
int k[arrsize];
fillArray(k);
create_file(k);
}
Usually you don't want to pass the whole array, instead you might want to pass a reference to it. 通常,您不希望传递整个数组,而是可能希望传递对其的引用。 I suggest you to use std::array instead of a C-style arrays.
我建议您使用std :: array而不是C样式的数组。
#include <array>
void fill(std::array<int, 1>& a)
{
a[0] = 0;
}
int main()
{
std::array<int, 1> a = {};
fill(a);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.