我需要知道二维数组的某个位置是否在其中。例如,我有一个 8x8 数组,用户需要在某个位置添加一个数字,例如 MyArray[3][7]
但首先我需要验证该位置是否在我的数组中。所以...我可以这样问吗?
if (MyArray[x - 1][y - 1]==NULL){
printf("Give me another location: \n");
.
.
.
}
最佳答案
如果用户输入了 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。
关于c - 如何知道某个位置是否在我的二维数组之外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27199186/