Reputation: 153
I am having this problem writing a function that when the user input x,y (the coordinate or index of two dimensional array) it will return 0 if there is nothing or 1 otherwise.
Upvotes: 1
Views: 4142
Reputation: 532
Others have answered the question on whether an element exists or not by checking for a sentinel value. These answers assume that the 2D array is already allocated. If your situation had a different mem allocation model (allocate 1D initially and allocate the 2D dynamically), then you would also have to check whether the 2D is actually allocated for any 1D index. 1D => first dimension; 2D => second dimension.
Upvotes: 0
Reputation: 1350
In order to do so, first thing you need to do is initializ the array. You can do it this way:
int i,j;
for (int i = 0; i<SizeX; i++) {
for (int j = 0; j<SizeY; j++) {
arr[i][j] = 0;
}
}
Now you can easly check it this way:
int check (int arr[SizeX][SizeY] , int i , int j) {
// out-of-bound check
if (i < SizeX && j < SizeY) {
return (arr[i][j] == NULL ? 0 : 1);
}else {
// -1 indicate error - out of bound indexes
return (-1);
}
}
Upvotes: 3
Reputation: 68
What do you mean by nothing?
If you dont initialize your arry, it contains garbage values,
but if you do, u can check whether the cell contains the original value or a diffrent
one, and then return 1 or 0.
Upvotes: 0