My code works perfectly in visual studio and Linux but i encounter a problem running it in Linux.
The function is about a dynamic array with a header file.
When I input number N, it prints prime numbers between 2 and N
Output:
I got only prime numbers under 10, when I used Linux.
Same code but different result!!
Please help me to know how I can get it fixed.
This is a part of the function:
#include <iostream>
#include "sieve.h"
#include <cstring>
using namespace std;
//prints all the prime numbers between 2 and N
Sieve::Sieve()
{
cout << "Enter the number of integers to input: ";
cin >> N;
arr = new bool[N 1];
memset(arr, true, sizeof(arr));
for (int p = 2; p * p <= N; p )
{
if (arr[p] == true)
{
for (int i = p * p; i <= N; i = p)
arr[i] = false;
}
}
return;
}
void Sieve::show()
{
cout << "Following are the prime numbers between 2 and "
<< N << endl;
for (int p = 2; p <= N; p )
if (arr[p])
cout << p << " ";
cout << endl;
}
Sieve::~Sieve()
{
delete[] arr;
}
CodePudding user response:
memset
comes from C, and is generally incompatible with bool
. It sets the memeory to a bitpattern, specifically static_cast<unsigned char>(true)
. There's no gurantee that static_cast<unsigned char>(true)
has the same bitpattern as true
.
std::fill
works with pretty much any element type and any container.
CodePudding user response:
sizeof(arr)
would never be equal to size of your allocated array. It would be equal to sizeof(bool*)
if arr
is a pointer or if arr
is some compound type that accepts pointer assignment, it's some different value, just never right one ...
Do not use memset
for bool
s. On some platform true might have "all ones" binary pattern, on other it is just 1, sizeof(bool)
may vary from 1 to 4 bytes. Use range-base filling (e.g. std::fill or plain for-loop), where arr
would be the "begin" of the range and arr N 1
would be the "end".