Using void * in C instead of overload?

My question is here: I saw this code for a multi-threaded application:

void Thread( void* pParams )
{  
    int *milliseconds = (int *)pParams;
    Sleep(milliseconds);
    printf("Finished after %d milliseconds", milliseconds); //or something like that
}

It really interested me, I knew that it was mallocsending back a pointer to void, and you can use it for whatever you want, does this mean that I can create a function that can accept any data types?

For example, a function that I wrote without testing:

void myfunc( void* param )
{  
    switch(sizeof(param)) {
       case 1:
       char *foo = (char *)param; break;
       case 2:
       short *foo = (short *)param; break;
       case 4: 
       int *foo = (int *)param; break;
    }
}
myfunc(3.1415);
myfunc(0);
myfunc('a');

Maybe I'm wrong, even if it works, is this a terrible practice? Thank.

+3
source share
5 answers

, void * . , , void *, . , , , , 2- enum, , INT, FLOAT, DOUBLE .. ..

#include <stdio.h>

typedef enum inputTypes
{
    INT,
    DOUBLE,
    CHAR
} inType;

void myfunc(void*, inType);

int main(void)
{
    int    i = 42;
    double d = 3.14;
    char   c = 'a';

    myfunc(&i, INT);
    myfunc(&d, DOUBLE);
    myfunc(&c, CHAR);

    return 0;
}

void myfunc(void* param, inType type)
{  
    switch(type) {
       case INT:
           printf("you passed in int %d\n", *((int *)param));
           break;
       case DOUBLE:
           printf("you passed in double %lf\n", *((double *)param));
           break; 
       case CHAR: 
           printf("you passed in char %c\n", *((char *)param));
           break;
    }
}

you passed in int 42
you passed in double 3.140000
you passed in char a
+7

, , , , .

myfunc, sizeof(param) : sizeof .

, , , , , , , , - . , void *, - .

void *: , , , . void * , .

+7

sizeof(param) , 8, 64- . , .

0

, sizeof(param) .

0

The size is void*completely dependent on the system and is determined at compile time, and not on what is actually contained within it.

0
source

Source: https://habr.com/ru/post/1779273/


All Articles