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; } 
5
  • 3
    Use C++ arrays such as std::array<int, arrsize> instead of C arrays like int [arrsize] and everything will start making much more sense. Commented Feb 6, 2018 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. Commented Feb 6, 2018 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. Commented Feb 6, 2018 at 14:39
  • 4
    your code never declared k Commented Feb 6, 2018 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). Commented Feb 6, 2018 at 15:06

2 Answers 2

2

You simply forget to define an array:

int main() { int k[arrsize]; fillArray(k); create_file(k); } 
Sign up to request clarification or add additional context in comments.

1 Comment

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; } 

1 Comment

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]);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.