I have the following code that works fine:
#include <stdio.h>
#include <stdlib.h>/*need this for rand()*/
#include "random.h"
#include <time.h>/*for time() function*/
int main()
{
int arr[5], a = 0;
printf("enter 5 array elements\n");
scanf("%d", &arr[0]);
scanf("%d", &arr[1]);
scanf("%d", &arr[2]);
scanf("%d", &arr[3]);
scanf("%d", &arr[4]); /*scan all elements*/
srand(time(NULL)); /*set the seed*/
a = arr[rand() % ARR_SIZE(arr)];/*from .h file*/
printf("%d\n",a);/*print the random element generated above*/
return 0;
}
It picks a random integer for an array of 5 integers.
I need the following modifications to it:
A function should accept two parameters — an array of void pointers and the array length. It should return a void pointer.
The function should pick an element from the array at random and return it.
int main() must seed the random number generator and then call the function. Then finally it should print the random element that was generated.
I don't know how to modify it to meet above requirements.
Here are the random.h file contents:
#define ARR_SIZE(arr) ( sizeof((arr)) / sizeof((arr[0])) )
This should do the trick.
void* getRandomElement(void** array, int size)
{
int* arr = (int*)*array;
return (void*)&(arr[rand() % size]);
}
int main(void)
{
int arr[5];
void* p = (void*)arr;
printf("enter 5 array elements\n");
scanf("%d", &arr[0]);
scanf("%d", &arr[1]);
scanf("%d", &arr[2]);
scanf("%d", &arr[3]);
scanf("%d", &arr[4]); /*scan all elements*/
srand(time(NULL)); /*set the seed*/
printf("random element %d\n", *(int*)getRandomElement(&p, ARR_SIZE(arr)));
return 0;
}