2013-03-30 19 views
-4

好吧,我創建的這個函數使用Eratosthenes算法來計算所有的素數< = n。該功能將素數和素數計數存儲在參數中。Eratosthenes算法的分割錯誤C

當函數退出時,素數應該指向一個動態分配的內存塊,其中包含所有質數< = num。 *計數將有素數計數。

這裏是我的功能getPrimes:

void getPrimes(int usernum, int* count, int** array){ 
    (*count) = (usernum - 1); 
    int sieve[usernum-1], primenums = 0, index, fillnum, multiple; 

    //Fills the array with the numbers up to the user's ending number, usernum. 
    for(index = 0, fillnum = 2; fillnum <= usernum; index++, fillnum++){ 
     sieve[index] = fillnum; 
    } 

    /*Starts crossing out non prime numbers starting with 2 because 1 is not a prime. It then deletes all of those multiples and 
    moves on to the next number that isnt crossed out, which is a prime. */ 
    for (; primenums < sqrt(usernum); primenums++){ //Walks through the array. 
     if (sieve[primenums] != 0){ //Check's if that number is 0 which means it's crossed out 
      for (multiple = (sieve[primenums]); multiple < usernum; multiple += sieve[primenums]){ //If it is not crossed out it starts deleting its multiples. 
       //Crossing multiples out and decrements count to move to next number 
       sieve[multiple + primenums] = 0; 
       --(*count); 
      } 
     } 
    } 
    int k; 
    for (k = 0; k < usernum; k++) 
    if (sieve[k] != 0){ 
     printf(" %d", sieve[k]); 
    } 
    printf(" "); 
    array = malloc(sizeof(int) * (usernum + 1)); 
    assert(array); 
    (*array) = sieve; 
} 

我在這裏的功能編譯完美,但我發現我有一個分段錯誤,當我嘗試從類似101的更大的數字。有沒有人看到我的代碼產生了分段錯誤?

+1

如果你在調試器中運行你的代碼,它會告訴你seg-fault在哪裏。更重要的是,你將能夠檢查變量的值等。 –

+0

如果有人可以幫助我,我會非常感激。 –

+2

你完全可以自己做這件事。就像我說的,在調試器中運行它。 –

回答

1

以下兩個語句是問題:

array = malloc(sizeof(int) * (usernum + 1)); 

我想你的意思做*array = malloc...,注意我array前加星號。您要取消參考int**參數,以便修改調用者的指針

(*array) = sieve; 

此代碼不復制陣列,它臨時本地變量的地址分配給呼叫者的指針sieve數組在函數結束時超出範圍後將不再存在。您想使用for循環將sieve中的內容複製到剛纔分配的內存塊中。

編輯:

我看到丹尼爾·菲捨爾已經指出的第二個問題,2小時前in a previous incarnation of your question