A function like that:
int * getRandom( ) {
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
Is this one possible to be used in Vivado HLS? If possible, how can I initialize an array of unknown size because I cannot use static
and malloc
anymore?
Converting comments into an answer.
You cannot, in standard C, return an array from a function — you can return a pointer OK (so the code shown is permissible, though it clearly has re-entrancy and threading issues). If you can't use static
or malloc()
et al, then you need to pass the array to the function for it to fill in instead of returning the array. Then it is the caller's responsibility to allocate the space.
See also srand() — why call it only once.
So you mean I can set a global array as function arguments and give value to each element so I can get the array without using
static
andmalloc
?
Yes, or a local array, or an any-other-type of array you care to think of. I think the appropriate implementation might be:
void getRandom(int n_vals, int *i_vals)
{
for (int i = 0; i < n_vals; i++)
i_vals[i] = rand();
}
but the possible variations are legion. You can reinstate the printing if you really want it; you can even call srand()
if you really want to (but you should only call that once). You can then use it like:
void somefunc(void)
{
int data[20];
getRandom(15, data);
…use data…;
}
or
static int data[20];
void somefunc(void)
{
getRandom(18, data);
…use data…;
}
or other variants (such as not using static
in front of the file-scope definition of data
— converting it into a global variable). (Yes, you'd probably use 10 as in the question, or 20 as the amount of space in the array — but 15 and 18 are also OK values in their context.)