I am trying to return an array from the function, it is working fine as long as I am using hard coded value for size of an array. However, when I change it to dynamic (getting calculated from nproc = sysconf(_SC_NPROCESSORS_ONLN);
) then I am getting following error:
-->gcc test.c
test.c: In function ‘getRandom’:
test.c:14:16: error: storage size of ‘r’ isn’t constant
static int r[nproc];
^
test.c:18:21: warning: implicit declaration of function ‘time’; did you mean ‘nice’? [-Wimplicit-function-declaration]
srand( (unsigned)time( NULL ) );
^~~~
nice
when I change static int r[10];
to static int r[nproc];
its failing. I need to keep the size dynamic as the its going to be runtime calculated. Can someone please help me to get through this problem ?
Code:
#define _GNU_SOURCE
#include <assert.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* function to generate and return random numbers */
int * getRandom(int nproc ) {
printf("nproc is %d\n",nproc);
//static int r[10];
static int r[nproc];
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;
}
/* main function to call above defined function */
int main () {
/* a pointer to an int */
int *p;
int i;
int nproc;
nproc = sysconf(_SC_NPROCESSORS_ONLN);
p = getRandom(nproc);
for ( i = 0; i < 10; i++ ) {
printf( "*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}
Need to know how to achieve this in C PROGRAMMING