Home > database >  how to convert int to void *?
how to convert int to void *?

Time:05-14

I'm trying to make an analogue of sscanf with a specifier %p.

I use this:

int res = ahex2num(buf);
*va_arg(ap, void **) = (void *) res;

It works correctly, i actually get the address i pass, like 0x1A but i am facing this error:

warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

In main function:

int main(){
    void *a;
    readFromStr("0x1A", "%p", &a);
    printf("%p", a); 
    return 0;
}

/*
out: 0x1a
*/

Can I somehow avoid this?

long ahex2num(unsigned char *in){
    unsigned char *pin = in;
    long out = 0;
    while(*pin != 0){
        out <<= 4;
        out  =  (*pin < 'A') ? *pin & 0xF : (*pin & 0x7)   9;
        pin  ;
    }
    return out;
}

CodePudding user response:

Apparently pointers, particularly void *, have a different size than int on your system. E.g., pointers may be 64 bits and int may be 32 bits. Implementing %p in a routine like sscanf is a valid reason for converting an integer to void *, but you need to use an integer type that can hold all the bits needed for a pointer. A good type for this may be uintptr_t, declared in <stdint.h>.

You will need to ensure all the code that works with the integers from the scanning, such as ahex2num, can support the necessary width and signedness, including handling potential overflow as desired.

CodePudding user response:

If I had your entire code, I could test it. I assume to remove the warning without using a pragma is as simple as changing your typecast from int to long int.

CodePudding user response:

I solved this problem like this:

long long int res = ahex2num(buf);
  • Related