I have passed a 2D array normally (by value) to a function "elem", which further passes it on to another function "interchange", which performs a row-interchange operation and displays it. But the problem is, after I return from interchange back to main(), the value of the array has been changed to the resultant array from interchange, even though technically they must be three different variables for three different functions (main, elem and interchange). Why is this so, and what can I do to make the array in main() remain unchanged?
//include files...
void interchange(float c[10][10],int m,int n)
{
int i,j,p,q;
float temp;
printf("\nEnter the two row numbers to interchange:");
scanf("%d%d",&p,&q);
if((--p<m)&&(--q<n))
{
for(i=0;i<m;i++)
{
temp=c[p][i];
c[p][i]=c[q][i];
c[q][i]=temp;
}
} else
{
printf("Row numbers must be less than matrix order.\n");
return;
}
printf("\nResultant matrix is:\n"); //print the array in interchange,c
printf("\n");
for(i=0;i<m;i++)
{for(j=0;j<n;j++)
{
printf("%f\t",c[i][j]);
}
printf("\n");
}
}
void elem(float b[10][10],int m,int n)
{
int ch;
do
{
printf("\n1:Row interchange\t 2:Exit elementary transformations\n\nEnter the choice:");
scanf("%d",&ch); //get user input to decide which operation to perform (there are more operations in actual code)
switch(ch)
{
case 1: interchange(b,m,n);
break;
case 2: printf("\nExiting elementary transformations.\n");
break;
}
}while(ch!=2);
}
int main()
{
float a[10][10];
int m,n,i,j;
printf("Enter the order of the matrix:");
scanf("%d%d",&m,&n);
printf("Enter the matrix elements:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%f",&a[i][j]);
}
}
//print the entered array a
printf("\n");
for(i=0;i<m;i++)
{for(j=0;j<n;j++)
{
printf("%f\t",a[i][j]);
}
printf("\n");
}
elem(a,m,n);
//print the original array in main()
printf("\n");
for(i=0;i<m;i++)
{for(j=0;j<n;j++)
{
printf("%f\t",a[i][j]);
}
printf("\n");
}
}
This is the output I got:
Enter the order of the matrix:2 2
Enter the matrix elements:1 2 3 4
1.000000 2.000000
3.000000 4.000000
1:Row interchange 2:Exit elementary transformations
Enter the choice:1
Enter the two row numbers to interchange:1 2
Resultant matrix is:
3.000000 4.000000
1.000000 2.000000
1:Row interchange 2:Exit elementary transformations
Enter the choice:2
Exiting elementary transformations.
3.000000 4.000000
1.000000 2.000000
Sorry for the shabby code, I salvaged it from a larger file.