简体   繁体   中英

What is the correct way to memset an array of pointers?

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;

ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM