I have below a structure and need to initialize the object of it using std::fill
.
typedef struct _test
{
char name[32];
char key[4];
int count;
}test;
As of now, I am using memset
. I need to change it to std::fill
. I have tried below but std::fill
throws compiler error for the structure object.
test t;
char a[5];
std::fill(a, a + 5, 0);
std::fill(t, sizeof(t), 0);
Note: I don't want to initialize using this way. char a[5] = {0};
You don't need std::fill
(or std::memset
, on which you should read more here). Just value initialize the structure:
test t{};
This will in turn zero initialize all the fields. Beyond that, std::fill
accepts a range, and t, sizeof(t)
is not a range.
And as a final note, typedef struct _test
is a needless C-ism. The structure tag in C++ is also a new type name. So what this does is pollute the enclosing namespace with a _test
identifier. If you need C compatibility on the off-chance, the way to go is this
typedef struct test
{
char name[32];
char key[4];
int count;
} test;
This sort of typedef is explicitly valid in C++, despite both the struct declaration and the typedef
declaring the same type name. It also allows both C and C++ code to refer to the type as either test
or struct test
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With