c - 如何知道某个位置是否在我的二维数组之外?

标签 c arrays matrix null multidimensional-array

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

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

最佳答案

如果用户输入了 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。

关于c - 如何知道某个位置是否在我的二维数组之外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27199186/

相关文章:

c - glib 的 g_atomic_int_get 的目的是什么?

python - Numpy:获取数组 X 的最低 N 个元素,仅考虑其索引不是另一个数组 Y 中的元素的元素

c++ - 结构中的 “Incomplete type is not allowed”错误

arrays - 从 Common Lisp 中的文本文件中读取数组

java - 遍历矩阵右对角线

python - numpy np.array 与 np.matrix(性能)

python - 从协方差矩阵中查找高斯拟合误差

c - 在 C 中使用 fwrite() 的 fseek() 之后,fread() 不工作

c - 使用 C for unix 使用线程根据给定根位置遍历文件系统

无法从 Windows 批处理脚本构建 C 程序