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;
}
}
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With