【问题标题】:How to know if a location is out of my 2D array?如何知道某个位置是否在我的二维数组之外?
【发布时间】:2014-11-29 05:27:10
【问题描述】:

我需要知道二维数组的位置是否不在其中。例如,我有一个 8x8 数组,用户需要在某个位置添加一个数字,例如MyArray[3][7],但首先我需要验证该位置是否在我的数组中。所以……我可以这样问吗?

if (MyArray[x - 1][y - 1]==NULL){
  printf("Give me another location: \n");
  .
  .
  .
}

【问题讨论】:

  • 你使用什么语言?
  • 我正在使用 C 语言 @ColinvH

标签: c arrays matrix null multidimensional-array


【解决方案1】:

如果用户输入了xy 的值,那么您可以执行以下操作:

#include <stdio.h>

int main() {
    int MyArray[8][8];

    int x, y;

    printf("Give me a location: ");
    scanf("%d %d", &x, &y);

    while (x < 0 || x > 7 || y < 0 || y > 7) {
        printf("Give me another location: ");
        scanf("%d %d", &x, &y);
    }

    return 0;
}

否则程序可能会尝试访问程序不应触及的内存空间并尝试检查它是否为 NULL。

【讨论】:

    【解决方案2】:

    您将需要传递数组的维度以及数组本身,并执行边界检查愚蠢的数学方法:

    if (x < 0 || x >= xlen || y < 0 || y >= ylen) {...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      相关资源
      最近更新 更多