Hey guys, so I'm trying to write a program that will calculate all the primes in a number up to n using the Sieve of Eratostheneus algorithm. I've written the code, it compiles with no errors or warning. However, when I try to run it the program closes. After doing some debugging I found that the source of the problem is coming from a method call (i'll state which method later) and a message in Visual Studio 2012 pops up saying Access Violation. However, the method I'm calling is set to public so I don't really understand what's happening. Any guidance would be appreciated!
I believe the error is occuring within the int sieveEratosthenes(LList* p, int lstSize) function and it's specifically occuring at the node->setPrime(false); call.
I believe the error is occuring within the int sieveEratosthenes(LList* p, int lstSize) function and it's specifically occuring at the node->setPrime(false); call.
//Class Declaration
class ListNode
{
friend class LList;
public:
ListNode(int item = 0, bool pVal = false, ListNode* link=nullptr);
int getItem() { return item_; }
bool getPrime() { return prime_; }
void setPrime(bool p) { prime_ = p; }
ListNode* getNext() { return link_; }
private:
int item_;
bool prime_;
ListNode *link_;
};
//function
int sieveEratosthenes(LList* p, int lstSize)
{
//locals
ListNode* node;
bool pTest = false;
//Populate the List
for(int j = 2; j < lstSize; j++) //Starts filling the list at 2
{
p->append(j, true); //Values are not considered prime until tested
cout << j << " has been added to the list." << endl;
}
//Algorithm
for(int i = 2; i < lstSize; i++)
{
node = p->_find(i - 2); //i - 2, sets position in list equal to value being evaluated
pTest = node->getPrime();
if(pTest) //if node value is prime
{
for(int j = 2 * i; j <= lstSize; j += i)
{
node = p->_find(j-2);
node->setPrime(false);
}
}
}
return 0;
}