Currently I am trying to fill an array of size num with random values. To do this, I need to create two functions:
1: Write a function (*createdata) that allocates a dynamic array of num double values, initialising the values to 0.0.
2: Write a different function (gendata) that will populate an array of double values with random values generated using the rand() function.
Here is my attempt at writing how the functions operate (outside main() ):
double *createdata(int num)
{
int i = 0;
double *ptr;
ptr = (double *)malloc(sizeof(double)*num);
if(ptr != NULL)
{
for(i = 0; i < num; i++)
{
ptr[i] = 0.0;
}
}
}
double gendata(int num)
{
createdata(num);
int j = 0;
for(j = 0; j < num; j++)
{
ptr[j] = rand();
}
}
However, I know that there is something certainly wrong with the above.
What I would like is that once I have called both functions in main, I will have generated an array of size num that is filled with random numbers.
You have to pass the allocated pointer to the
gendatafunction, because in it’s current form,ptris unknown. Does that even compile?Example:
And:
Also note I’m checking for return
NULLagain frommalloc.Other hints others might say here:
malloc.freethe pointer after you use it entirely.gendata, but you declared it asdouble. Usevoidinstead if you’re not going to return anything.But you’re probably gonna need to return the pointer from it anyways, so that you can use it later in other functions, such as
main.EDIT: So, this would be like this, as an example:
And in your
main: