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

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    225

    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;
    }
    
    void saddle(int a[M][N])
    {
     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)
    		cout<<"\n\nSaddle Point 
    
    :"<<min[0];
     }
    }
    int main(void)
    {
     int a[M][N]={5,7,3,7,7,9,7,1,2};
     
     saddle(a);
    
     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. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    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...
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM