can anyone tell me the difference between ‘memset’ and ‘fill’ in c++?
I quite confused why my code doesn’t work with ‘memset’ but does with ‘fill’
I haven’t had this problem, so I don’t know why this is happening
can anyone help me?
thank you! :))
I’m making a Sieve of Eratosthenes like usual but it keep giving me this number ‘72340172838076673’
I was expecting a series of 1s and 0s for my sieve
but it kept returning ‘72340172838076673’
here’s my code :
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';
}
}````
mya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
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.
2