简体   繁体   中英

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). 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.

#include <array>

void fill(std::array<int, 1>& a)
{
    a[0] = 0;
}

int main()
{
    std::array<int, 1> a = {};
    fill(a);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM