Santiago Páez Santiago Páez - 1 year ago 67
C Question

How to know if a location is out of my 2D array?

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

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");

Answer Source

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 num, x, y;

    printf("Give me a number: ");
    scanf("%d", &num);

    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download