If you want to find out garbage values (or non-garbage values), first, you must define what is a garbage value.
Eg:- If your array will only have unsigned values then you can use a negative value (-1, -2, -3....) as your garbage value.
int arr[10];
int garbage = -1;
for(int i=0; i < 10; i++)
{
arr[i] = garbage;
}
for(int i=0; i < 10; i++)
{
if(arr[i] == garbage)
{
}
else
{
}
}
Alright pal, now this method works fine, but what if I can't use any value in the range of
int
as the garbage value ?
Well, for this case, the following approach is suitable. Just read the following code, you'll understand the mechanism.
typedef struct {
int value;
bool is_used; }MyArray;
MyArray arr[10];
for(int i=0; i < 10; i++)
{
arr[i].value = 0;
arr[i].is_used = false;
}
for(int i=0; i < 10; i++)
{
if(arr[i].is_used == true)
{
}
else
{
}
}
The first approach if more efficient when you know the range of your valid input values, if not the second method is more clear, simple and understandable.