If I have pointers of type T (T*)
and I have an array of them T* array[N]
will these two methods allow me to later check which entries are null pointers to lazily initialize stuff in each bucket?
memset(array, 0, sizeof(T*)*N);
or
for (int i = 0; i < N; ++i)
array[i] = NULL;
i.e. will the memset
call also let me later do if (array[i] == NULL) ...
?
I wouldn't want to introduce undefined behavior if not..
Although a null pointer value isn't technically required be all zero bits I'm not aware of any system where it's not all zero bits. So either method should work.
However there's an easier way to initialize an array which will set the correct null pointer values even on some evil implementation:
T *array[N] = {};
Or if you dynamically allocate it:
T **array = new T*[N]();
Formally, the memset
approach doesn't work, because there is no requirement that a null pointer be represented by the value 0
in memory. In practice it works fine.
Better than both: std::uninitialized_fill
; the standard library implementor can do things that you can't to optimize performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With