/* Calculating minimum and maximum element out of a list of elements using Recursion
Input: A list of numbers
Output: Minimum and Maximum number
*/
#include<stdio.h>
int a[8]={6,2,3,9,1,0,11,8},size=8;
int * minmax(int beg,int end)
{
int res[2],*x,*y,mid;
printf("%d %d %p:",beg,end,res);
if(beg==end)
{
res[0]=a[beg];
res[1]=a[beg];
return res;
}
if(end-beg==1)
{
if(a[beg]<=a[end])
{
res[0]=a[beg];
res[1]=a[end];
}
else
{
res[0]=a[end];
res[1]=a[beg];
}
printf("%d %d",res[0],res[1]);
printf("\n");
return res;
}
printf("\n");
mid=(beg+end)/2;
x=minmax(beg,mid);
y=minmax(mid+1,end);
if(x[0]<=y[0])
res[0]=x[0];
else if(x[0]>y[0])
res[0]=y[0];
if(x[1]<=y[1])
res[1]=y[1];
else if(x[1]>y[1])
res[1]=x[1];
printf("OUT: %d %d %d %d WIN: %d %d\n",x[0],y[0],x[1],y[1],res[0],res[1]);
return res;
}
int main()
{
int i,j,min,max,*ans;
ans=minmax(0,size-1);
printf("Ans=%d %d",ans[0],ans[1]);
return 0;
}
In the above code to get minimum and maximum element using recursion, the array res is getting same address in successive recursive calls as shown below:
0 7 0xbfa9cb08:
0 3 0xbfa9cac8:
0 1 0xbfa9ca88:2 6
2 3 0xbfa9ca88:3 9
OUT: 3 3 9 9 WIN: 3 9
4 7 0xbfa9cac8:
4 5 0xbfa9ca88:0 1
6 7 0xbfa9ca88:8 11
OUT: 8 8 11 11 WIN: 8 11
OUT: 8 8 11 11 WIN: 8 11
Ans=8 11
At function calls minmax(0,1) and minmax(2,3) res gets same address and that is why it creates problem. Similar thing can be observed at minmax(4,5) and minmax(6,7)
Why this is happening and how can I modify the program to get minimum and maximum
resis declared asint res[2]in your function, yet youreturn res;upon exit. . Any caller that utilizes the result, including yourself via recursion, invokes UB.structwith two fields.void minmax(int beg,int end, int *pMin, int *pMax)and not even use a struct. People seem to have an aversion to returning values through pointers. Is it because they learned Java first?