-4
#include <iostream> 
int *parray(int a[100][100],int m , int n) 
{   int b[200],i, t , j;
    i = 1;
    j = t = 0;
    for(int i = 0; i < m ; i++)
    for(int j = 0; j < n ; j++)
    b[t++] = a[i][j];

    //      for(int i = 0; i < m*n ; i++)      
    //      std::cout<<b[i]<<' ';
    return b;
}

int main()
{
  int a[100][100],m,n,*b;
  std::cin>>m>>n;

  for(int i = 0; i < m ; i++)
  for(int j = 0; j < n ; j++)
   std::cin>>a[i][j];

  b = parray(a,m,n);

  for(int i = 0; i < m*n ; i++)
   std::cout<<b[i]<<' ';

  return 0;
}

when input is

     2 2 1 2 3 4 

output is

     1 2 612675848 32767

but when I remove the two "//" just before the return of parray() function the output becomes:

     1 2 3 4 1 2 3 4

Can someone please tell me why code works when I print the value before passing?

jymspaul
  • 3
  • 3

1 Answers1

0

int b[200] in parray() is local to parray(). It is removed from the stack from the function returns.(when the scope is over).

If you access it later in main() ,you get undefined behavior.

Sagar D
  • 2,588
  • 1
  • 18
  • 31