动态数组大小未知 [英] dynamic array with unknown size
问题描述
我想用C写一个程序,用户键入2个数字a和b。
I want to write a program in C where the user types in 2 numbers a and b.
0℃; A< INT_MAX
0 < a < INT_MAX
A&LT; B&LT; INT_MAX
a < b < INT_MAX
这个软件可以检查多少素数是如何在A和B之间,并保存所有的人都在一个动态数组。
The program checks how many Prime numbers are in between a and b and saves all of them in a dynamic array.
对于的malloc
函数我需要的数组的大小,这意味着我必须先检查所有的数字,如果他们是一本正经的数字只是为了获得数组的大小,
然后用的malloc()
,
再检查一遍所有的数字填补了数组。
是否有可能使这个运行速度更快,而不是做同样的事情两次?
For the malloc
function I need the size of the array, which means I have to first check all numbers if they are prim numbers just to get the size of the array,
then use malloc()
,
and then check all numbers again to fill the array.
Is there any possibility to make this run faster and not doing the same thing twice?
for (int i = a; i <= b; i++)
{
if (check_if_prime(i) == 0)
size++;
}
primze_numbers = malloc(size*sizeof(int));
int j = 0;
for (int i = a; i <= b; i++)
{
if(check_if_prime(i) == 0)
{
prime_numbers[j] = i;
j++;
}
}
推荐答案
由于尺寸是在开始时未知的,对于一个多元件的尺寸分配的空间低效
Since the size is unknown in the beginning, allocating the space for the size of one more element is inefficient.
一个可能的解决方案是:重新分配空间(使用的realloc
)的previous尺寸大小的两倍只要大小是不够的。
One possible solution is: reallocate the space(Use realloc
) twice the size of the previous size whenever the size is not enough.
Real size - Space size
0 0
1 1
2 2
3 4
4 4
5 8
6 8
7 8
8 8
9 16
10 16
... ...
这种方式,重新分配的次数并不多,你不浪费太多的空间。
This way, the times of reallocation is not much, and you don't waste much space.
这篇关于动态数组大小未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!