I already asked a question regarding a program. I got an answer but I have a new issue. The program I wrote is not working and I don't know why.
The function is working fine (I guess) but I want to be sure by printing the values of each element of the array and see if they are correct (I will need this for other purposes).
I tried with a simple for instruction for a printf, but the array seems to be empty. The problem may be related to the memory address of the value I want to print.
Please have a look, any advice will be welcome!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int * rand_gen(int N, float fl_value); // Function declaration
int main() // Main function
{
int N; // Declaration: Number of trials
printf("Number of trials: ");
scanf("%d", &N); // Asks for Number of trials
float alpha = 0.3;
float beta = 0.4;
float gamma = 0.5;
float delta = 0.6;
int i; // Index
int seed = time(NULL); // Random number generator seed (based on current time)
srand(seed);
// Populate arrays
float *bin_array_alpha[] = { rand_gen( N, alpha ) };
float *bin_array_beta[] = { rand_gen( N, beta ) };
float *bin_array_gamma[] = { rand_gen( N, gamma ) };
float *bin_array_delta[] = { rand_gen( N, delta ) };
// Here I would like to print the elements of the arrays, something like:
for ( i=0 ; i<N ; i++)
{
printf("\nbin_array_alpha[%d] = %f",i,bin_array_alpha[i]);
printf("\nbin_array_beta[%d] = %f",i,bin_array_beta[i]);
printf("\nbin_array_gamma[%d] = %f",i,bin_array_gamma[i]);
printf("\nbin_array_delta[%d] = %f",i,bin_array_delta[i]);
printf("\n");
}
// Free the memory
static const size_t m = sizeof(bin_array_alpha)/sizeof(bin_array_alpha[0]);
for ( size_t i = 0 ; i < m ; ++i )
{
free(bin_array_alpha[i]);
free(bin_array_beta[i]);
free(bin_array_gamma[i]);
free(bin_array_delta[i]);
bin_array_alpha[i] = NULL;
bin_array_beta[i] = NULL;
bin_array_gamma[i] = NULL;
bin_array_delta[i] = NULL;
}
printf("\n");
return(0);
}
// Function: generate an array populated by: array[j] = rand()*fl_value
int * rand_gen(int N, float fl_value)
{
int *array;
array = (int *)malloc(sizeof(float)*N);
if(array == NULL)
{
printf("\nRun out of memory!\n");
exit(1);
}
int j;
float x;
for( j = 0 ; j < N ; j++ )
{
x = rand(); // Generates a random number
x = x/RAND_MAX; // 0 < x < 1
x = x * fl_value;
array[j] = x; // array[j] = x * fl_value
}
return array;
}
The result is always the same (for example N=3):
bin_array_alpha[0] = 0.000000
bin_array_beta[0] = 0.000000
bin_array_gamma[0] = 0.000000
bin_array_delta[0] = 0.000000
bin_array_alpha[1] = 0.000000
bin_array_beta[1] = 0.000000
bin_array_gamma[1] = 0.000000
bin_array_delta[1] = 0.000000
bin_array_alpha[2] = 0.000000
bin_array_beta[2] = 0.000000
bin_array_gamma[2] = 0.000000
bin_array_delta[2] = 0.000000
Thank you so much again!
arraytype inrand_genisint *?[]after each of the 4 declarations. The function returns a pointer, although, itsint*pointer is incompatible with afloat*pointer..