Your overall design is flawed. You should not treat NULL as a catch-all zero value. NULL is a special pointer value, not simply an integer. If you compare an int against NULL, you're comparing two different types, which is not a good idea. Furthermore, you're comparing a scalar type with a pointer type, which is even worse.
Values in this array can also be 0 which is causing some trouble for me.
If this is the case, you cannot use 0 as both a value and a "mark" for "non present value". Problem is, you cannot use NULL either, because it's a different type. If you try using it, the compiler will warn you (or at least it should, if you enable warnings). At best, assigning NULL will implicitly convert it to int and result in 0 since NULL is usually defined just as ((void *)0), so it will be impossible to distinguish between NULL-ed values and valid values.
You will have to reserve one of the values between INT_MIN and INT_MAX for this purpose:
#include <limits.h>
enum { NOT_PRESENT = INT_MIN };
int size = 4;
int *numbers = malloc(size * sizeof(int));
// Initialize all to NOT_PRESENT
for (int i = 0; i < size; i++)
numbers[i] = NOT_PRESENT;
// Fill some fields
numbers[0] = 3;
numbers[1] = 0;
numbers[2] = 6;
// Search and find min value's index
int min = 0;
for (int i = 0; i < size; i++) {
if (numbers[i] != NOT_PRESENT) {
if (numbers[i] < numbers[min]) min = i;
} else {
// Code if value is not present here
}
}
printf("%d\n", min);
0is just an integer literal, whileNULLis((void *)0)intvalue againstNULLwhen you really want to compare against0. 99.44% of systems,NULLis zero, but it's not a guarantee. Also, most systems do:#define NULL ((void *) 0), so the compiler should flag the comparison of anintvalue against a pointerNULL, even if the internal representation of a null pointer of that type is not all bits zero.