hi guys

is it timeconsuming to use memset instead of for?

i mean suppose we have an array of int

int prime[200000];

we use memeset(prime, 200000, 0, sizeof(prime))

also we can use
for(i = 0; i < 200000; i++)
prime = 0;

If either method is faster, it will be memset(). memset() is a compiler provided function, and it might use tricks to run as fast as possible on the target platform.

hi guys

is it timeconsuming to use memset instead of for?

i mean suppose we have an array of int

int prime[200000];

we use memeset(prime, 200000, 0, sizeof(prime))

also we can use
for(i = 0; i < 200000; i++)
prime = 0;

I would expect memset() to be optimized for the machine it was compiled on...

Edited 6 Years Ago by gerard4143: n/a

Use memset() to initialize a block of memory to a specified value.
Because this function can use only a type char as the initialization value, it is not useful for working with blocks of data types other than type char, except when you want to initialize to 0.
In other words, it wouldn't be efficient to use memset() to initialize an array of type int to the value 99, but you could initialize all array elements to the value 0.

Perhaps a more interesting question is why you have a 200000-element array that needs initializing in the first place.

If you want to initialize the array to 0 then just declare it like this: int prime[200000] = {0}; and the compiler will most likely use the optimal way to initialize it.

Actually for an array with program lifetime (i.e. one not declare in a function or declared static in a function) you don't even need the = {0} . The compiler initialises all such arrays and variables to 0 if no other value is given.

This article has been dead for over six months. Start a new discussion instead.