Reputation: 418
I can't really use a vector for this so I'm stuck with an array im having difficulty using..
string whitelist[256][1];
fill_n(whitelist, sizeof whitelist / sizeof **whitelist, "NULL");
I have also tried memset but it doesn't work in the sense that it wants an int and not a string, I have also tried
whitelist[256][1] = {{0}};
however I do not believe it worked...I don't care if 0, 1 is initialized but I need it to initiliaze the 256...
ALTERNATIVELY, I need to check if there's a value inside of whitelist[200] even if it's uninitialized, I would prefer this but from my research it cannot be done to check if it's NULL/empty.
Upvotes: 0
Views: 50
Reputation: 56567
In general, for an array of type T arr[M][N]
, you can do either:
T arr[M][N]{}; // C++11 or later
which will value-initialize the whole 2-D array with the default constructor, or, similarly for C++98,
T arr[M][N] = {}; // C++98
However, in your case the type std::string
provides a default constructor, then the definition
string whitelist[256][1];
uses that default constructor for every element, so each element in the array has a determinate value (i.e. the empty string), hence you can safely use them. This is of course in strike contrast to POD types, for which the value is indeterminate and you need to use {}
to zero them.
Note that you can even you use something like
string whitelist[256][1] = {"first", "second"};
and the rest of the elements will be default-constructed.
Small example to convince yourself:
#include <iostream>
struct Foo
{
Foo(int) {std::cout << __PRETTY_FUNCTION__ << std::endl;}
Foo() {std::cout << __PRETTY_FUNCTION__ << std::endl;}
};
int main()
{
Foo arr[2][3] = {1,2}; // calls the int ctor 2 times, default ctor 4 times, as expected
(void)arr; // to remove warning of non-used variable
}
Upvotes: 3
Reputation: 320671
An array declaration with std::string
elements, like
string whitelist[256][1];
will already automatically initialize each array element using std::string
's default constructor (which creates an empty string). There no need to do anything.
Your apparent belief that without extra effort you'll somehow end up with "uninitialized" strings has no basis in reality.
Upvotes: 0