I try to fullfill a vector (which i have to allocate) with random numbers between -0.8 and 0.8. My question is why in the main function when i call the function setvector() does not return the vector and i still take the initialized with zeros? Thanks a lot. here what i did
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void allocate(double **a, int size) {
*a = malloc(size);
}
double setvector(double *v){
int i, seed, send_size;
send_size = 10;
allocate(&v, send_size * sizeof(double)); // allocate memory for the vector
seed = time(NULL);
srand(seed);
for (i = 0; i < send_size; i++)
{
v[i] = 1.6*((double) rand() / (double) RAND_MAX) - 0.8;
}
printf("Inside function the vector is:\n\n");
for (i = 0; i < 10; i++)
{
printf("The %d element has the random %4.2f\n", i, v[i]);
}
return *v;
}
int main(){
double *v = NULL;
setvector(v);
printf("\nThe vector from main is:\n\n");
printf("The 1st element of v is %4.2f\n", &v[0]);
printf("The 1st element of v is %4.2f\n", &v[1]);
return 0;
}
Here is my screen output:
Inside function the vector is:
The 0 element has the random -0.79
The 1 element has the random -0.34
The 2 element has the random 0.48
The 3 element has the random -0.67
The 4 element has the random -0.70
The 5 element has the random 0.61
The 6 element has the random -0.67
The 7 element has the random -0.66
The 8 element has the random -0.44
The 9 element has the random -0.36The vector from main is:
The 1st element of v is 0.00
The 1st element of v is 0.00
In
mainyou’re passing the addresses of the array elements toprintf:That should be
printf(..., v[0]);.Further:
doesn’t change
vinmain, sovremainsNULLthere. You should havesetvectortake adouble**, likeallocate, and pass it the address ofv.