I want to create a function that returns a random array. When I already know the size of the array, I do it in the following way:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int* random_vector();
void print_array(int size, int vector[]);
int main()
{
int size = 10;
srand(time(NULL));
int *vector;
vector=random_vector();
print_array(size, vector);
return 0;
}
int* random_vector()
{
static int vector[10];
for(int i=0; i<10; i )
{
vector[i]=rand();
}
return vector;
}
void print_array(int size, int vector[])
{
for(int i=0; i<size; i )
{
printf("%d ", vector[i]);
}
printf("\n");
}
The problem is that when I do not know the size, and I try to keep the size as a parameter of the function (in other words, I want to declare int* random_vector(int size)
) it returns an error: storage size of 'vector' isn't constant
.
How can I solve this?
(for completeness, below I show how I have been dodging the problem so far, using a void
function)
void random_zero_to_nine(int size, int vector[]);
void print_array(int size, int vector[]);
int main()
{
int size = 10;
int vector[size];
srand(time(NULL));
random_zero_to_nine(size, vector);
print_array(size, vector);
return 0;
}
void random_zero_to_nine(int size, int vector[])
{
for(int i=0; i<size; i )
{
vector[i]=rand();
}
}
CodePudding user response:
You can't declare an array with a variable size, as you are trying to do with the random_vector function. Instead, you can use dynamic memory allocation to create an array of the desired size at runtime. Here's one way you could implement your random_vector function using dynamic memory allocation:
int* random_vector(int size)
{
int *vector = malloc(sizeof(int) * size); // Allocate memory for the array
for(int i=0; i<size; i )
{
vector[i]=rand();
}
return vector;
}
In this implementation, we use the malloc function to allocate the necessary amount of memory for the array, based on the size parameter. Since malloc returns a pointer to the allocated memory, we can return this pointer from the random_vector function and use it in the same way as a statically-declared array.
You should also keep in mind that when you use dynamic memory allocation, you are responsible for freeing the allocated memory when it is no longer needed. In this case, you would need to call the free function on the pointer returned by random_vector once you are done using the array, like this:
int main()
{
int size = 10;
int *vector = random_vector(size);
print_array(size, vector);
free(vector); // Free the memory that was allocated by random_vector
return 0;
}
By using dynamic memory allocation, you can create an array of the desired size and use it in your code without having to resort to using a void function.