gpt4 book ai didi

C - 返回未知大小的数组

转载 作者:太空狗 更新时间:2023-10-29 14:55:04 25 4
gpt4 key购买 nike

假设我想编写(在 C99 中)以下函数:

NAME: primes
INPUT: an integer n > 0
OUTPUT: int array filled with the prime numbers in range [2, n]

我怎样才能从我的函数中返回这样一个数组?那可能吗?


请注意,我希望调用者分配一个 n * sizeof(int) 数组,我将用 0(复合)和 1(质数)填充).

我不能只返回一个指向数组的指针,因为调用者无法知道数组的长度:

int * primes(int n)
{
int * arr = malloc(n * sizeof(int));
// do stuff
return arr;
}

int main(void)
{
int * arr = primes(100);
printf("%lu \n", sizeof arr); // prints 8
}

而且我不能像这样更改签名:

int (*primes(int n))[LENGTH]  

因为 LENGTH 在编译时是未知的。


我在某处读到类似“返回带有数组的结构是一个可怕的想法”之类的内容,而且,好吧......那是我最后的想法。

在这种情况下,最佳做法是什么?

最佳答案

如果您调用的函数必须决定它需要分配的实际元素数量,您应该传递一个指向已分配长度的指针以及其余参数,如下所示:

size_t actual_length;
int *arr = primes(100, &actual_length);
if (arr == NULL) {
... // Report an error
}
for (size_t i = 0 ; i != actual_length ; i++) {
printf("%d\n", array[i]);
}

素数 看起来像这样:

int *primes(int count, size_t *actual_length) {
size_t primes_needed = ...
int *res = malloc(sizeof(*res)*primes_needed);
*actual_length = primes_needed;
// Do calculations, perhaps some reallocs
// Don't forget to reassign *actual_length = ... on realloc
...
return res;
}

关于C - 返回未知大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19301715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com