I need to create a vector of which I do not know the number of components at the moment of the declaration. For example, suppose that the vector will contain the prime numbers below a given n
and I cannot know how many there are before actually evaluating them.
Whenever I allocate memory with malloc
, I know that the memory can later be freed using free
:
int main(int argc, char** argv)
{
int* p=malloc(4*sizeof(int));
for(int j=0; j<4; j++)
{
*(p+j)=2*j;
}
printf("%d %d %d %d\n", *p, *(p+1), *(p+2), *(p+3));
free(p);
return 0;
}
My idea was to allocate more memory than I what I need, and then to free only a portion of it. So, naively I would like to do something like int* p=malloc(1000*sizeof(int))
(supposing that I know for sure that p
will have less than 1000 components) and then use free(p+j)
where j
is the number of meaningful components that I have given to p
after the computation. But that is not allowed.
Of course, there is always the possibility of making a list instead, using struct
, and create the array only at the end, but I don't like that solution, it seems convoluted to me.
What is the right way to create an array when I only know an upper bound for its size at the time of declaration, in case the size of the array will only be determined at the end?