【问题标题】: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
arrays
matrix
null
multidimensional-array
【解决方案1】:
如果用户输入了x 和y 的值,那么您可以执行以下操作:
#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) {...