c-在2d数组中检查null [英] c - Checking for null in a 2d array

查看:166
本文介绍了c-在2d数组中检查null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从输入文件填充10 x 10的字符网格. 我需要检查网格是否为正方形(即具有N x N个字符,其中N< = 10)

I am filling a 10 x 10 grid of characters from an input file. I need to check if the grid is a square (i.e, has N x N characters, where N <= 10)

输入文件如下:

pitk
olpe
pkey
tope

在gdb中打印网格时,得到以下结果:

When I print the grid in gdb, I get the following result:

$1 = {"pitk\000\000\000\000\366h", 
      "olpe\000\000\001\000\000", 
      "pkey\000\000\000\000\000", 
      "tope\000\000\000\000\000", 
      "\000\344\241\367\377\177\000\000", <incomplete sequence \336>, 
      "\000\377\377\177\000\000\037\355\336", <incomplete sequence \367>, 
      "\000\177\000\000\000\000\000\000\000", 
      "\000\000\000\000\000\000\000\000\000", 
      "\000\000\000\000\000\000\000\000\r\020", 
      "\000\000\000\000\000\000\000\000\000"}

我的主要功能检查网格是否有效的部分是:

The part of my main function that checks if the grid is valid, is:

  bool check = (checknxn(grid));
  if(check == false) {
    fprintf(stderr, "Invalid Input!\n");
    exit(0);
  }

checknxn函数:

The checknxn function:

bool checknxn(char grid[10][10]) {
  int columns = 0;
  for(int i=0;i<10;i++) {
    if(grid[0][i]!=NULL)
      columns++;
    else {
      break;
    }
  }

  for(int i=1;i<10;i++) {
    for(int j=columns;j<10;j++) {
    if(grid[i][j]!=NULL)
      return false;
    }
  }

  int rows = 0;
  for(int i=0;i<10;i++) {
    if(grid[i][0]!=NULL)
      rows++;
    else {
      break;
    }
  }
  if (!(rows == columns))
    return false;
  for(int i=0;i<rows;i++) {
    for(int j=0;j<columns;j++) {
      if(grid[i][j]==NULL) {
        return false;
      }
    }
  }
  return true;
}

这将返回false,即使在这种情况下输入网格有效,我的程序也会退出.

This returns false, and my program exits, even though the input grid in this case is valid.

在这种情况下,我不知道为什么checknxn函数返回false.

I can't figure out why the checknxn function is returning false in this case.

更新:这是初始化网格的方式:

UPDATE: This is how I initialize my grid:

FILE *file1 = fopen(argv[1], "r"); // "r" for read

  char grid[10][10];

  char c;
  for(int i=0;i<10;i++){
    for(int j=0;j<10;j++){
      fscanf(file1,"%c", &c);
      if (c == '\n') {
        grid[i][j] = '\0';
        break;
      }
      if (c == ' ') {
        grid[i][j] = '\0';
        continue;
      }
      if (c == '\0') {
        grid[i][j] = '\0';
        continue;
      }
      else {
        grid[i][j] = c;
      }
    }
  }

推荐答案

不初始化数据的经典C错误. Memset可能要走的路(见下文).

Classic C mistake of not initializing data. Memset probably the way to go (see below).

memset(grid, 0, sizeof(grid[0][0]) * rows * columns);

这篇关于c-在2d数组中检查null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆