0

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;
}
A.Petrov
  • 33
  • 1
  • 6
  • 3
    Use C++ arrays such as `std::array` instead of C arrays like `int [arrsize]` and everything will start making much more sense. – nwp Feb 06 '18 at 14:37
  • 2
    When you do something like e.g. `int k[arrsize]` as an argument, the compiler will translate it to `int* k`. You don't really pass arrays, you pass pointers to their first elements. – Some programmer dude Feb 06 '18 at 14:38
  • 3
    And what do you mean by "I cannot pass the same array"? ***How*** can you not "pass the same array"? Do you get build errors? Wrong results? Crashes when running? Please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). – Some programmer dude Feb 06 '18 at 14:39
  • 4
    your code never declared k – Swift - Friday Pie Feb 06 '18 at 14:40
  • 1
    Off-Topic: You don't need to use precompiled headers. Precompiled headers may save you some build time on large and huge projects, but for small projects, they are not worth the hassle (IMO). – Thomas Matthews Feb 06 '18 at 15:06

2 Answers2

2

You simply forget to define an array:

int main() {
    int k[arrsize];

    fillArray(k);
    create_file(k);
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Look as [what-is-the-difference-between-a-definition-and-a-declaration](https://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration). Btw, here it is both. – Jarod42 Feb 06 '18 at 14:49
1

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;
}
  • No worries about "passing the whole array". C style arrays always decay to pointers unless you explicitly set the size in the method definition i.e. `void foo::bar(int (&fooArray)[20]);` – Justin Randall Feb 06 '18 at 15:36