c - 使用函数和双指针编写一个程序来查找给定矩阵是否为空?

标签 c matrix

在下面的程序中,函数调用后执行停止,请告诉我原因以及如何解决这个问题。

#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() 函数实际检查 null。我会将其更改为:

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/

相关文章:

opencv - 在 OpenCV 中生成随机数矩阵

c++ - 如何在实例化数组类后插入整个数组 [C++]

c - 如何检查一个元素在矩阵(C)中是否存在多次?

c - 异或加密的限制

c - 从标准输入段错误中获取输入

C char 双指针

java - 为实时目的在 zeromq 中统一

c - 仅使用 For 循环反转字符串

Java,矩阵溢出

java - 想要JAVA中mxn矩阵中的所有对角线