Thread: why can't i return Array from function?

1. why can't i return Array from function?

Hello,
I m trying to find saddle point in a matrix. But when i return array from function the program simply doesn't work at all. I get no output even though there's a saddle point in matrix. Here is the code :-

Code:
```#include <iostream.h>
#define M 3
#define N 3
int* find_min(int a[M][N],int row)
{
int *temp,j=1;
temp=new int[2];
temp[0]=a[row][0];
temp[1]=0;
for(j=1;j<N;j++)
{
if(temp[0]>a[row][j])
{
temp[0]=a[row][j];
temp[1]=j;
}
}
return temp;
}
int find_max(int a[M][N],int col)
{
int i,temp;
temp=a[0][col];
for(i=1;i<M;i++)
{
if(a[i][col]>temp)
temp=a[i][col];
}
return temp;
}

{
int i,max,*min,j;
for(i=0;i<M;i++)
{
min=find_min(a,i);
max=find_max(a,min[1]);
if(min[0]==max)

:"<<min[0];
}
}
int main(void)
{
int a[M][N]={5,7,3,7,7,9,7,1,2};

return 0;
}```
This code works perfectly now when i write the above function as :-

Code:
```int* find_min(int a[M][N],int row)
{
int temp[2],j=1;
temp[0]=a[row][0];
temp[1]=0;
for(j=1;j<N;j++)
{
if(temp[0]>a[row][j])
{
temp[0]=a[row][j];
temp[1]=j;
}
}
return temp;
}```
this is not working. Can anybody tell me why is this wrong?

2. Can anybody tell me why is this wrong?
because local vars do not exist after the function is finished, so returning pointer or reference to the local var makes no good

use some suitable class instead (std::vector, or 2D array) and return it by value...

Popular pages Recent additions