2

having an array:

char* arr[some_size] = {nullptr};

and later initializing some of its elem's is there any way that I can reset this array in other way than iterate over its elements and set them to nullptr?
I would like to avoid this:

for(unsigned i = 0; i < some_size;++i)
{
arr[i] = nullptr;
}

3 Answers 3

7

You can either iterate over it yourself, or you can call a function that iterates over it for you:

#include <algorithm>

// choose either one:
std::fill_n(arr, some_size, nullptr);
std::fill(arr, arr + some_size, nullptr);

One way or another, iteration must occur.

Sign up to request clarification or add additional context in comments.

3 Comments

funny that there isn't same way of nullifying array after this array had been initialized. I can do this: T* arr[size] = {nullptr}; but later after this array has been initialized I cannot to arr[size] = {nullptr};
@Nawaz I'm more than happy to use more modern ver, so in this sense I don't see a problem.
Iteration still occurs when you initialize it, SmallB. It's just that the compiler generates the code for it instead of you or the standard-library authors.
4

Rob's answer will work for C++. If you're doing straight up C, look into memset() or bzero().

char *arr[size] = { NULL };
...
memset(arr, 0, sizeof(char *) * size);
/* or */
bzero(arr, sizeof(char *) * size);

memset (standard C) is generally preferred over bzero (being a BSD-ism).

3 Comments

The (minor) problem either of those functions is that we have to assume a null pointer is represented by all-bits-zero, which isn't necessarily the case.
@Rob, while technically true, can you think of any architecture where it is not zero?
@Eda, please see comp.lang.c FAQ 5.17. They're not common systems, which is why I said this is a minor problem.
0

I think that Cuthbert's answer is good. There is also the ZeroMemory WinAPI function (For windows).

Comments

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.