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

1

Good, I have a problem in C, I want to cast a float to a void * and then in another function to cast it from void * to float, the problem is that it is printing 0.0. For what is this?

char * i = "1.22";
float numeroFlotante = (float) strtod(i,NULL); //Hace un cast de un char* a float
insertarInstruccion(&numeroFlotante, 3); //3 se refiere al tipo de dato, en este caso float.

void insertarInstruccion(void* valor, int tipo){
//ACA INSERTA ESTE DATO Y OTROS EN UNA ESTRUCTURA (PILA).

} 

void imprimirPila(){
    struct Pila *temp = pPila;
    while (temp != NULL){
        if(temp->tipo == 0){ //Si el tipo es 0 es int
            int z = (int) temp->dato;
            printf("%i\n", z);
        }
        else if(temp->tipo == 3){ //ACA ME IMPRIME 0,0.
            float valor = *(float*) &temp->dato;
            printf("%f\n",valor);
        }
        else{
            printf("%s\n", (char*) temp->dato);
        }
        temp = temp->sig;
    }
}
    
asked by alex22596 18.04.2017 в 18:41
source

1 answer

0

What happens that you are not casting the structure correctly

float valor = *(float*) &temp->dato;

What you are doing there is to obtain the memory address where the attribute called "data" is found, then convert it to a floating type pointer and finally access the content of that conversion.

What you should have done would be this

float valor = *((float*)(temp->dato));

To understand the context I made this small example based on your published code.

#include <stdio.h>
#include<stdlib.h>

typedef  struct{
    void* dato;
    int tipo;
}Objeto;


void insertarInstruccion(Objeto* pObjeto, void* valor, int tipo){
    pObjeto->dato=valor;
    pObjeto->tipo=tipo;
}


int main()
{
    Objeto* pObjeto= malloc(sizeof(Objeto));

    char * i = "1.22";
    float numeroFlotante = strtof(i,NULL);

    //casteamos el numero a void* y lo asignamos al struct
    insertarInstruccion(pObjeto,(void*)(&numeroFlotante),3);

    //realizamos el proceso inverso
    float valor= *((float*)(pObjeto->dato));
    printf("El valor es %f\n",valor);

    return 0;
}

I hope it helps you solve your doubts since the object of type struct is used as a pointer and memory is stored dynamically, which could be useful for your stack type structure.

PS: Do not forget to free the memory using the free function.

    
answered by 18.04.2017 / 19:28
source