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; }
std::array<int, arrsize>instead of C arrays likeint [arrsize]and everything will start making much more sense.int k[arrsize]as an argument, the compiler will translate it toint* k. You don't really pass arrays, you pass pointers to their first elements.