-4

好的,所以我创建的这个函数使用 Eratosthenes 算法来计算所有素数 <= n。该函数在参数中存储素数和素数。

当函数退出时,素数应该指向一块动态分配的内存,其中包含所有素数<= num。*count 将有素数的计数。

这是我的函数 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 开始的更大数字时出现分段错误。有谁看到我的代码在哪里产生分段错误?

4

1 回答 1

1

以下两个语句是有问题的:

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

我认为你的意思是*array = malloc...,请注意我之前添加的星号array。您想取消引用int**参数以修改调用者的指针

(*array) = sieve;

此代码不会复制数组,它会将临​​时局部变量的地址分配给调用者的指针。该sieve数组在函数结束时超出范围后将不再存在。您想使用for循环将内容复制sieve到刚刚分配的内存块中。

编辑:

我看到 Daniel Fischer 已经在 3 小时前在您问题的前一个化身中指出了第二个问题。

于 2013-03-30T02:26:02.170 回答