mya
mya

Reputation: 1

memset() vs. std::fill()

Can anyone tell me the difference between memset() and std::fill() in c++?

I am quite confused why my code doesn't work with memset() but does with std::fill().

I am making a Sieve of Eratosthenes like usual and I was expecting a series of 1s and 0s for my sieve but it keeps giving me this number '72340172838076673'

Here is my code :

#include <bits/stdc++.h>
using namespace std;
long long s[2000009],a[1000009],i,j,n;
void seive(int N) {
    j = 1;
    memset(s,1,sizeof(s));
    s[0] = 0;
    s[1] = 0;
    for(int i = 2; i <= sqrt(N); i++) {
        if(s[i] == 1)
            for(int j = i * i; j <= N; j += i) {
                s[j] = 0;
            }
    }
}

int main () {
    ios_base::sync_with_stdio(false); cin.tie(NULL);
    cin>>n;
    seive(2e6);
    for (i = 1 ; i <= n ; i++) {
       cin>>a[i];
       cout<<s[a[i]]<<'\n';
    }
}

Upvotes: -2

Views: 162

Answers (1)

Mike Nakis
Mike Nakis

Reputation: 61949

The documentation for std::fill() says:

Assigns val to all the elements in the range [first,last)."

This means that std::fill will work with any data type.

On the other hand, the documentation for memset() says:

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

This means that memset() will only work with bytes. If your array of values is not an array of bytes, or if the value to fill with is not a byte, they will still both be interpreted as bytes, which means that you are highly unlikely to get anything meaningful.

Upvotes: 2

Related Questions