How to use void pointer as return type In C function

So, I plan to write a function to return a random array element. The function takes two parameters - an array of void pointers and the length of the array. It should return a pointer to the void. The idea is to take the given array, which comes in the form of an array of void pointer, the function will return a random element of the array. The question I have is, what do I need to do to return the pointer, what do I need to do for the "result" so that I can return it like that? After the wards, what do I need to do to access it again? Thanks

Here is what I did, but I get:

 "25: error: invalid use of void expression"

with warnings like:

" warning: pointer of type ‘void *’ used in arithmetic"

My code is:

#include<stdlib.h>
#include<stdio.h>
#include<time.h>
void *randomNum(void * array, int length)
{
    void * result;  
    result=array[rand()%(length-1)];
    return result;
}    
int main()
{
int i;
srand(13);
int array[9]={1,5,6,85,132,65463,1354,5863,134};

for (i=0;i<9; i++)
{
    printf("%d\n",*randomNum(array,9));
}



return 0;
}
+4
4

, :

    result = array[rand()%(length-1)];

void array, result. , , - :

    result = array + rand()%(length-1);

, , void, ( sizeof(void)==1 ). -void , , , , , , . , void, , .

void *randomNum(void * array, size_t size, size_t length)

, array char, array 1 :

    result = (char*)array + (rand()%(length-1)) * size;
                   ^                            ^

randomNum randomNum(array, sizeof(*array), 9)

, .

    printf("%d\n", *(int*)randomNum(array,sizeof(*array),9));
+4

:

1) array void *, length - . , , , , , .

( , , , array[index] *(array + index); void * void. .)

2) void *randomNum(array, 9). ; , .. *((int *)randomNum(array, 9)), , , randomNum, void, , :

int *randomNumInt(int *array, size_t length)
+1

(, ): *randomNum(array,9)

, randomNum void *, . , . , .

, randomNum void*, int. void *, - og memory - . int*, segfault.

0

void, *randomNum(array,9) . , - void.

0

All Articles