0

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 ??

1
  • 1
    Nope, not possible with a single call to memset. Use std::fill. Commented Aug 24, 2014 at 21:02

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

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.