[英]Passing array as an argument from one function to another in C++?
我有一個要在其中傳遞數組的程序-在本例中為k[arrsize]
,它是funciton fillArray()
到另一個函數create_file()
(同一數組,用隨機數填充)。 但是,我不能傳遞相同的數組,我想問一下如何做到這一點?
#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;
}
您只是忘了定義一個數組:
int main() {
int k[arrsize];
fillArray(k);
create_file(k);
}
通常,您不希望傳遞整個數組,而是可能希望傳遞對其的引用。 我建議您使用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.