0

I am not understanding is this function given below is cal by reference or value? Its working like call by reference. But I wonder if I am not passing any address or pointer then why the values are changing in main? Secondly, I would like to know how to write a function If I want the changes made inside a function to an array shouldn't reflect main? (I complied this code on gcc)

void assign(int n, int m, double a[n][m])
{
   int i, j;
   for(i=0;i<n;i++)
     for(j=0;j<m;j++)
      a[i][j]=i*10;
}
void main(void)
{
   int i,j,m,n;
    m=5;n=10;
   double a[n][m];
   for(i=0;i<n;i++)
     for(j=0;j<m;j++)
      a[i][j]=i*100;

   assign(n,m,a);
   for(i=0;i<n;i++)
   {
     for(j=0;j<m;j++)        
       printf("%f ",a[i][j]);        
    printf("\n");
   }
 }
  • 1
    https://stackoverflow.com/questions/6567742/passing-an-array-as-an-argument-to-a-function-in-c – Bill Lynch Jul 05 '17 at 05:48
  • If you pass a variable by reference, the function acts like it is a pointer. Therefore changes will be reflected in the array in main(). If you want to pass by reference, and not have the changes reflected in main(), you could either pass an element by value, or inside the function copy the whole array, and work on that array. – Ramon van der Werf Jul 05 '17 at 05:54
  • By the way, does this code compile? does the compiler understand `void assign(int n, int m, double a[n][m])` ? types of functional parmeters _n_ and _m_ are not defined here. – Ramon van der Werf Jul 05 '17 at 05:56
  • Thanks to both yes it compiled and run successfully (on cygwin gcc) – makarand kulkarni Jul 05 '17 at 06:00

0 Answers0