Anc*_*rya 0 c pass-by-reference multidimensional-array
我通常将2D数组(按值)传递给函数“ elem”,然后将其进一步传递给另一个函数“ interchange”,该函数执行行交换操作并显示它。但是问题是,在我从交换返回到main()之后,数组的值已从交换更改为结果数组,即使从技术上讲它们对于三个不同的函数(main,elem和interchange)必须是三个不同的变量)。为什么会这样,我该怎么做才能使main()中的数组保持不变?
//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");
}
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
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
Run Code Online (Sandbox Code Playgroud)
对不起,对于破旧的代码,我从一个大文件中挽救了它。
对于函数参数,不能 “按值”传递数组。
当编译器看到参数声明时float c[10][10],会将其转换为float (*c)[10]。
因此,传递的是一个指针(指向数组的第一个元素)。您修改指针所指向的内存,这会在调用函数中反映出来。
为什么会这样呢?
是的,您正在“按值”传递它,但是您必须了解C中的含义。当将数组传递给函数时,它将衰减为指针。然后,该指针按值传递,但该值是数组中第一个元素的地址。
我该怎么做才能使main()中的数组保持不变?
一些不同的事情,取决于您想要什么。您可以在函数中创建一个临时数组,然后复制所有值。将开头替换为:
void interchange(const float arr[10][10],int m,int n) {
float c[10][10];
for(int i=0; i<10; i++)
for(int j=0; j<10; j++)
c[i][j]=arr[i][j];
Run Code Online (Sandbox Code Playgroud)
并且只要没有其他错误,您的代码就会按照您想要的方式工作。加入的const有,如果你想一个元素分配,你会得到一个编译错误的效果arr的东西。