Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ references array

I wounder how i can make this code work?

#include <iostream>
using namespace std;

void writeTable(int (&tab)[],int x){
    for(int i=0;i<x;i++){
        cout << "Enter value " << i+1 <<endl;
        cin >> tab[i] ;
    }
}


int main(void){
    int howMany;
    cout << "How many elemets" << endl;
    cin >> howMany;

    int table[howMany];
    int (&ref)[howMany]=table;
    writeTable(ref,howMany);
    return 0;
}

And here are the errors that I have:

|4|error: parameter ‘tab’ includes reference to array of unknown bound ‘int []’|
|18|error: invalid initialization of reference of type ‘int (&)[]’ from expression of type ‘int [(((unsigned int)(((int)howMany) + -0x00000000000000001)) + 1)]’|
|4|error: in passing argument 1 of ‘void writeTable(int (&)[], int)’|

Thanks for help

like image 324
John Avatar asked Oct 16 '10 16:10

John


1 Answers

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

like image 63
Armen Tsirunyan Avatar answered Nov 05 '22 02:11

Armen Tsirunyan