c++ references array
If you are intending to pass the size of the array, then remove the reference
void f(int a[])
is equivalent to
void f(int* a)
so no copying will be done, if that is the concern.
If you want to take an array by reference, then you MUST specify the dimension. e.g.
void f(int (&a)[10])
Naturally, the best of the two is the third solution, which is to use std::vector's and pass them by reference, reference to const or by value if needed. HTH
Here is a slightly more C++ style of doing it:
#include <iostream>#include <vector>void writeTable(std::vector<int> &tab){ int val; for (unsigned int i=0; i<tab.size(); i++) { std::cout << "Enter value " << i+1 << std::endl; if (std::cin >> val) { tab[i] = val; } }}int main(){ int howMany; std::cout << "How many elements?" << std::endl; std::cin >> howMany; std::vector<int> table(howMany); writeTable(table); return 0;}
You need not specify the dimension of the array if you make writeTable
a function template.
template <typename T,size_t N>void writeTable(T (&tab)[N]) //Template argument deduction{ for(int i=0 ; i<N ; i++){ // code .... }}
.
int table[howMany]; // C++ doesn't have Variable Length Arrays. `howMany` must be a constantwriteTable(table); // type and size of `table` is automatically deduced