【问题标题】:What is causing this function to return nothing sometimes?是什么导致此函数有时不返回任何内容?
【发布时间】:2022-11-30 03:42:41
【问题描述】:

我有这个函数,它应该返回一个从 2 到 n 的素数数组,但有时它不返回任何东西,如果输入超过 3 或 4 的值,它只会说“exited with code=3221225477”。当它返回时工作,它跳过数字 5 并打印“2 3 29541 7 11 ...”。

有人可以指出它有什么问题吗?

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int *primes_in_range(int stop){
    int *array_primes = malloc(sizeof(int));
    int size = 1;
    int aim;
    int prime;

    array_primes[0] = 2;

    for (int number = 3; number <= stop; number += 2){
        aim = sqrt(number);

        for (int index = 0; index < size; index++){
            prime = array_primes[index];

            if ((number % prime) == 0){
                break;
            }
            else if (prime >= aim){
                array_primes = realloc(array_primes, sizeof(int)*size);
                array_primes[size] = number;
                size += 1;
                break;
            }
        }
    }
    return array_primes;
}

int main(){
    int *result = primes_in_range(8);
    
    for (int i=0; i<8; i++) printf("%d\n", result[i]);
    free(result);

    return 0;
}

我在 python 中按照相同的算法编写了一个程序,它没有跳过任何数字,所以它一定是出于不同的原因,除非我错过了什么,否则它不起作用。

我将在此处保留有效的 Python 代码:

def primes_in_range(stop: int = None):
    prms = [2]

    for num in range(3, stop+1, 2):
        aim = num**0.5

        for prm in prms:
            if not num % prm:
                break
            elif prm >= aim:
                prms.append(num)
                break

    if stop >= 2:
        return prms
    else:
        return []


print(primes_in_range(13))

【问题讨论】:

  • 错误(十六进制)C0000005 是访问冲突错误,通常由缓冲区溢出引起。
  • 这个array_primes = realloc(array_primes, sizeof(int)*size); array_primes[size] = number; 超出了数组边界。允许的最大值为 size-1
  • 另一个问题是 main猜测数组有多长。
  • 你从size = 1开始,然后在没有先增加大小的情况下调用了realloc,所以内存总是一个int太小了。
  • 谢谢,这解决了问题。

标签: c primes


【解决方案1】:
array_primes = realloc(array_primes, sizeof(int)*size);
array_primes[size] = number;
size += 1;

这不是将元素附加到数组的方式。正确的版本可能是:

size += 1; // first increase the size
array_primes = realloc(array_primes, sizeof(int)*size); // realloc to new size
array_primes[size-1] = number; // access last element, as usual

您还返回一个数组,但调用者不知道它的大小是多少。要么返回包含数组及其大小的结构,要么通过地址传递大小以填充(输出参数)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    相关资源
    最近更新 更多