Reputation: 13
I need to know if a location of a 2D array is out of it. For example i got a 8x8 array and the user needs to add a number in a location, for example MyArray[3][7]
but first i need to verify if that location is in my array. so... can i ask that like this?
if (MyArray[x - 1][y - 1]==NULL){
printf("Give me another location: \n");
.
.
.
}
Upvotes: 0
Views: 58
Reputation: 2130
If the value of x
and y
are entered by the user then you could do something like this:
#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;
}
Otherwise the program could try to access to a memory space that the program shouldn't touch and try to check if it is NULL.
Upvotes: 2
Reputation: 537
You will need to pass around the dimensions of the array along with the array itself, and do bounds checking the dumb mathy way:
if (x < 0 || x >= xlen || y < 0 || y >= ylen) {...
Upvotes: 1