昨天最后一道转置矩阵没能用二维数组函数传递实现,今天补上,第一个为正确的写法,第二个为找错误原因在原来的基础上修改成3*3数组转置
#include <stdio.h>
#include <stdlib.h>
int enter(int** array_pointer, int r,int c);
int trans(int r,int c, int** array_pointer);
int trans(int r,int c, int** array_pointer) {
int i=0,j=0;
int b[c][r];
for(i=0;i<c;i++)
for(j=0;j<r;j++)
{
b[j][i]=array_pointer[i][j];
}
printf("Transpose of your matrix:\n");
for(i=0;i<c;i++)
for(j=0;j<r;j++)
{
printf("%2d",b[i][j]);
if(j==r-1)
printf("\n");
}
return 0;
}
int enter(int** array_pointer, int r,int c) {
int i=0,j=0;
printf("Please enter the matrix:\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
scanf("%d", &array_pointer[i][j]);
printf("%2d", array_pointer[i][j]);
if(j==c-1)
printf("\n");
}
return 0;
}
int main()
{
int r=0,c=0;
int i=0;
printf("Please enter the rows(<=10) and columns(<=10) of the matrix:");
scanf("%d %d", &r, &c);
int** array_pointer;
array_pointer = (int **)malloc(r * sizeof(int*));
for (i=0; i<r; ++i) {
array_pointer[i] = (int *)malloc(c * sizeof(int));
}
enter(array_pointer, r, c);
trans(r,c,array_pointer);
for(i = 0; i < r; i++) {
free(array_pointer[i]);
array_pointer[i] = NULL;
}
if (array_pointer != NULL) {
free(array_pointer);
}
return 0;
}
运行结果:
原有基础修改
#include<stdio.h>
typedef int(*aa)[3];
aa enter(int r,int c);
int trans(int r,int c,int a[r][c]);
int main()
{
int r=0,c=0;
printf("Please enter the rows(<=10) and columns(<=10) of the matrix:");
scanf("%d %d",&r,&c);
int (*a)[c];
a=enter(r,c);
trans(r,c,a);
return 0;
}
aa enter(int r,int c)
{
int i=0,j=0;
static int a[3][3];
printf("Please enter the matrix:\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
printf("%2d",a[i][j]);
if(j==c-1)
printf("\n");
}
return a;
}
int trans(int r,int c,int a[r][c])
{
int i=0,j=0;
int b[c][r];
for(i=0;i<c;i++)
for(j=0;j<r;j++)
{
b[j][i]=a[i][j];
}
printf("Transpose of your matrix:\n");
for(i=0;i<c;i++)
for(j=0;j<r;j++)
{
printf("%2d",b[i][j]);
if(j==r-1)
printf("\n");
}
return 0;
}
运行结果:
错误分析: 静态变量定义错误,导致程序崩溃
完毕!