I'm currently writing a function that returns an array but it keeps showing [Warning] address of local variable 'bestIdx' returned [-Wreturn-local-addr] while compiling. What does this mean?
Below is the function I wrote:
int *findMostPrefered(int toyCnt, int childrenCnt, int prefer[][20], bool toyNum[], bool childrenNum[]){
int max = prefer[0][0], bestIdx[2]={0};
for(int i=(childrenCnt-1); i>=0; i=i-1){
if(childrenNum[i] == 0){
for(int j=(toyCnt-1); j>=0; j=j-1){
if(toyNum[j] == 0){
if(prefer[i][j] >= max){
max = prefer[i][j];
bestIdx[0] = i;
bestIdx[1] = j;
}
}
}
}
}
return bestIdx;
}
You declared the block scope array
bestIdxwith automatic storage durationthat will not be alive after exiting the function. So the returned pointer to the first element of the array will be invalid. Dereferencing such a pointer invokes undefined behavior.
Instead of the array with two elements you could use an object of the type
std::pair<int, int>and return it. For example