Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

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

like image 297
Palace Chan Avatar asked Oct 04 '12 21:10

Palace Chan


Video Answer


2 Answers

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]();
like image 117
bames53 Avatar answered Oct 16 '22 10:10

bames53


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.

like image 27
Pete Becker Avatar answered Oct 16 '22 12:10

Pete Becker