ARRAY-Initialize

How to Initialize whole array(Big Size) at once to zero without using any loop ??

I.e without calling each and every element of array and then initializing it.

using memset

void* memset( void* dest, int ch, std::size_t count );

example:

int arr[100];

memset (arr,0,sizeof(arr));

initialises all elements of array to 0.

But this will increase execution time since its a built in function memset()…

@wrangler00 The very first advice i’ll like to give you is, for asking questions on someone’s answer, please follow up comments below that. Don’t create a separate answer for each and delete the unnecessary ones. This keeps the forum clean.

Now, to answer you library version of memset is usually faster as compared to the version you’ll write. The first and sec answers here explains the fact completely. The main point is when you’ll write, your comiler will write one byte at a time. Using memset, hardware has different techniques like bit blit operations to set large chunks of memory to some value almost instantly(faster than the one you’ll write). Also, when you’ll write(manually), the memory addresses will have to be mapped individually in every iteration and various other checks which will slow it down.

you can use fill_ n(array_name,size_of_array,value_to_be_assigned) method

@wrangler00

There are many ways to initialize array!

int array[100] = {0};

says “set the first element to -1 and the rest to 0” since all omitted elements are set to 0 if you specify at least one.

  1. To set them all to 0, you can use something like [std::fill_n][1]

    std::fill_n(array,size,0);

  2. memset is not recommended, as will cause TLE for large array.

memset will not work for non-zero numbers, because it works on a byte level

you can write something like this…

int i;
for(i = SIZE; i--;)
    v[i] = 0;

Hope it helps!

Thank you :slight_smile:
[1]: std::fill_n - cppreference.com

It’s very easy.

int arr[100] = {};

The empty initializer causes the compiler to aggregate-initialize all of the elements of the array.

NOTE
This will work only in C++, not C

will increase execution time @aad@09…

Memset is much faster because it’s written in assembler while fill is just a template, so it gets reduced to linear loop only.

Sorry…I was not aware of that

I’d like to mention one point here, some compilers reduce the call to fill in memset(I read this on net once, don’t know if it actually does or how can I check the same) but in those cases it is matter of your system and compiler. And so, it may not make much difference.