How to cast from a struct to a void * and vice versa in C?

1

Good, I'm doing a program that reads a Python Bytecode file and executes the instructions given in it. The problem that I have right now is that I need to put a tag type structure into a stack. The stack only admits the type void * because there you can store anything like int, float ... What is the correct way to cast a struct to a void * and vice versa?

void LOAD_GLOBAL(char * nombreEtiqueta){
    struct Etiqueta *temporal = buscarEtiqueta(nombreEtiqueta);
    insertarElementoPila((void*) &temporal, 6);
}

struct Etiqueta *CALL_FUNCTION(int numParams){
    struct Etiqueta *P = (struct Etiqueta*) pPila;
    return P;
}
    
asked by alex22596 04.05.2017 в 05:40
source

1 answer

1
  

How to cast from a struct to a void * and vice versa in C?

You do not need an explicit conversion since void * can point to any type of data, you have an example in the comparison functions (callbacks) used with qsort :

int compare(const void *p1, const void *p2)
{
    const struct profile *elem1 = p1;    
    const struct profile *elem2 = p2;

    if (elem1->soc < elem2->soc)
        return -1;
    else if (elem1->soc > elem2->soc)
        return 1;
    else
        return 0;
}

Another thing is when we want to access its value (dereference) without using an intermediate pointer:

void fn(void *p)
{
    int x = *(int *)p;

    printf("%d\n", x);
}

int a = 5;
fn(&a);

In this case if we had to make an explicit cast to int * since we can not dereference a pointer to void * directly (in addition to the alignment we need to know the size of the passed type and void * does not give us no clue about that size, it's the cast who tells the compiler)

    
answered by 04.05.2017 / 13:20
source