Shìpu Ahamed
Shìpu Ahamed

Reputation: 480

initialize struct array element with different value using memset in c++

In C++,

struct info
{
    int lazy,sum;
}tree[4*mx];

Initialize :

memset(tree,0,sizeof(tree))

That means

tree[0].sum is 0 and tree[0].lazy is 0 ...and so on.

Now I want to initialize different value like this:

tree[0].sum is 0 and tree[0].lazy is -1 .... and so on.

In For loop

for(int i=0;i<n;i++) // where n is array size
{
    tree[i].sum=0;
    tree[i].lazy=-1;
}

but in memset function I can't initialize structure array with different value. is it possible ??

Upvotes: 0

Views: 757

Answers (1)

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48447

To memset you pass value that every byte of a given address range is initialized with.

memset - Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).

As such, you cannot achieve what you want.

This is what a constructor is for:

struct info
{
    int lazy,sum;
    info() : lazy(-1), sum(0) {}
} tree[4*mx];

// no need to call memset

Or you can create a pattern of the struct and set it to every element of your tree:

#include <algorithm>

struct info
{
    int lazy,sum;
} tree[4];

info pattern;
pattern.lazy = -1;
pattern.sum = 0;

std::fill_n(tree, sizeof(tree)/sizeof(*tree), pattern);

Upvotes: 3

Related Questions