8

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

2
  • 7
    The correct way is not to have that abomination in the first place in C++. Please, choose either C++ or C when asking a question like this. Commented Oct 4, 2012 at 21:11
  • Even in C there is another alternative: T* array[N] = {NULL}; Commented Oct 4, 2012 at 21:38

2 Answers 2

11

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]();
Sign up to request clarification or add additional context in comments.

1 Comment

@Seth : The null character must be represented with all zero bits (§2.3/3), but §3.9.2/3 says "The value representation of pointer types is implementation-defined."
2

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.

12 Comments

Can != will. Still +1 for introducing me to std::uninitialized_fill.
If you want to fill the array with null pointers, why would you prefer std::uninitialized_fill over std::fill?
@jamesdlin : A default-initialized array of pointers is in fact uninitialized, so std::uninitialized_fill is more pedantically correct even if unnecessary in this case.
Sweet I didnt' know of those!
@jamesdlin std::uninitialized_fill and std::uninitialized_copy use placement new to construct the elements they are initializing. std::fill and std::copy use assignment to already constructed objects. The difference is irrelevant to trivially constructible types such as pointers.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.