I have an allocated array and need to go over all fields and compare non null values. Values in this array can also be 0 which is causing some trouble for me.
int size = 4;
int *numbers = (int*) malloc(size * 4);
// 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] != NULL) {
if (numbers[i] < numbers[min]) min = i;
} else {
// Code if value is null here
}
}
printf("%d\n", min);
Im not sure how to compare properly with NULL. What is the correct way?
CodePudding user response:
Ur allocated array elements will never be NULL. Even the memory that is freed from using free function is not NULL. IT can points to anything may be any ur own program address space or outside address space.
Ur code looks OK. The value that u did not assigned to element at index 3 can have garbage but not NULL
CodePudding user response:
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);