在下面的程序中,函数调用后停止执行。告诉我原因以及解决方法。
#include<stdio.h>
int checkNull(int **a,int m,int n)
{
int null=0,i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(a[i][j]==0)
null++;
return null;
}
int main()
{
int a[10][10],null,i,j,m,n;
printf("Enter the number of rows in the matrix");
scanf("%d",&m);
printf("\nEnter the number of columns in the matrix");
scanf("%d",&n);
printf("\nEnter the elements in the matrix");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nThe matrix is");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
}
null=checkNull((int **)a,m,n);
if(null==m*n)
printf("\nThe matrix is null");
else
printf("\nThe matrix is not null");
return 0;
}
最佳答案
最好让checkNull()
函数实际检查是否为空。我将其更改为:
int checkNull(int a[][10],int m,int n)
{
int i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(a[i][j]!=0)
return 0;
return 1;
}
然后,调用将如下所示:
if(checkNull(a,m,n))
printf("\nThe matrix is null");
else
printf("\nThe matrix is not null");
但是从问题来看,您似乎想对这个问题使用双指针。如果创建了一个指向每一行的指针数组,然后动态分配所有内容,那将很有意义。这也具有适用于任何大小矩阵的优点。类似于以下内容:
#include <stdio.h>
#include <stdlib.h>
int checkNull(int **a, int m, int n)
{
int *row, i, j;
for(i=0; i<m; i++)
{
row = a[i];
for(j=0; j<n; j++)
if(row[j] != 0)
return 0;
}
return 1;
}
int main()
{
int **a, i, j, m, n;
printf("Enter the number of rows in the matrix");
scanf("%d", &m);
a = (int **)malloc(sizeof(int *) * m);
printf("\nEnter the number of columns in the matrix");
scanf("%d", &n);
printf("\nEnter the elements in the matrix");
for(i = 0; i < m; i++)
{
a[i] = (int *)malloc(sizeof(int) * n);
for(j = 0; j < n; j++)
scanf("%d", a[i] + j);
}
printf("\nThe matrix is");
for(i = 0; i < m; i++)
{
printf("\n");
for(j = 0; j < n; j++)
printf("%d ", a[i][j]);
}
if(checkNull(a, m, n))
printf("\nThe matrix is null");
else
printf("\nThe matrix is not null");
return 0;
}
关于c - 编写程序以使用函数和双指针查找给定矩阵是否为空?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29786785/