smallB
smallB

Reputation: 17110

How to nullify an array?

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;
}

Upvotes: 2

Views: 6158

Answers (3)

C.J.
C.J.

Reputation: 16081

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

Upvotes: 0

David Cuthbert
David Cuthbert

Reputation: 41

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

Upvotes: 4

Rob Kennedy
Rob Kennedy

Reputation: 163257

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.

Upvotes: 7

Related Questions