Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Technicalities involved with array of references

I wrote this code for the following problem. My compiler is givin me the following error- [Error] declaration of 'a' as array of references. What is the problem?

void repfunc(int& a[],int size){

    for(int i=size-1;i>=0;--i){

            if(a[i]==0){
                a[i]=1;
                return;
            }

        for(int j=i-1;j>=0;--ji){

            if(a[i]==a[j]&&a[i]!=9){
                ++a[i];
                a[i]%=10;
                return;
            }
            else if(a[i]==a[j]&&a[i]==9){
                a[j-1]++;
                a[j-1]%=10;

                    FOR(k, 1,size-j){
                        a[k]=k;
                    }

                return;
            }
        }

    }

}

like image 645
Soumadeep Saha Avatar asked Mar 21 '23 11:03

Soumadeep Saha


2 Answers

As the error says, you can't have an array of references. It looks like you're actually trying to pass an array by reference. You can (sort of) do that by changing it to take a pointer to the start of the array:

void repfunc(int a[], int size)  // equivalent to "int * a"

Since arrays are convertible to pointers, this will do the right thing if the argument is an array

int a[4] = {1,2,3,4};
repfunc(a, sizeof a / sizeof a[0]);

Alternatively, you could accept a reference to an array of the correct size:

template <size_t size>
repfunc(int (&a)[size])

allowing the size to be deduced automatically

int a[4] = {1,2,3,4};
repfunc(a);

but note that this will only work if a is actually an array; not, for example an pointer to a dynamically allocated array.

like image 63
Mike Seymour Avatar answered Mar 24 '23 00:03

Mike Seymour


C++ Standard 8.3.2/4 clearly says that:

There shall be no references to references, no arrays of references, and no pointers to references

Actually a reference must always refer to something - there is no such thing as a null reference. This is why there can be no arrays of references, as there is no way to default instantiate references inside an array to a meaningful value. -Source is Here.

And also By origin array is accessed via pointer arithmatic. So if we want to support array of reference we have to support pointer to reference, as per standard which is not possible. These are reason array of reference is not possible. Which is what you were doing.

And as Mike Seymour mentioned : void repfunc(int a[], int size) is perfectly ok for your case.

like image 43
deeiip Avatar answered Mar 24 '23 00:03

deeiip