No, there’s no way to tell whether an array element has been initialized or not.
You could use calloc()
instead of malloc()
, this automatically initializes everything to 0
, so you could do:
if (array[0] == 0) {
array[0] = 5;
} else {
array[0] *= 3;
}
But this won’t work if 0
is a valid value in your array.
Instead of an array of integers, you could use an array of structs, and put an initialized
field in the struct.
struct element {
int initialized;
int value;
};
After allocating the array, you’ll need to fill in the initialized
field in all the elements, to show that the values aren’t yet initialized.
array = malloc(N * sizeof(struct element));
for (int i = 0; i < N; i++) {
array[i].initialized = 0;
}
Then you can do:
if (!array[0].initialized) {
array[0].value = 5;
array[0].initialized = 1;
} else {
array[0].value *= 3;
}
solved How Do I Check If An Element In An Array Is An Address? [closed]