简体   繁体   中英

Void Pointer Cast Error?

I am working with a void pointer in my c program. I have a if statement that forces the printing of a data set to a 32-byte boundary.

** I should note, that I'm trying to modify the address of the mem pointer to shift it to a boundary **

I'm getting the following error thrown:

Operation between types "void*" and "int" is not allowed

My code is as follows:

if(((int)mem % 32) != 0)   
    mem -= ((int)mem % 32);

where mem is defined as:

void *mem

Something like this:

void * mem;                   // input

char * p = mem;               // byte-wise arithmetic
uintptr_t n = (uintptr_t) p;  // integral arithmetic

p -= n % 32                   // align

mem = p;                      // output

Note that this assumes that the memory before the address mem points to has already been allocated and is also yours.

You can of course compress the code into a single statement:

mem = (char *) mem - ((uintptr_t) mem % 32);

Beware that the pointer conversions are generally implementation defined. There's no standard way to reason about "alignment", and the integral value obtained from a pointer may or may not have anything to do with the layout of the memory in the hardware.

You cannot do pointer arithmetics with a void * :

mem -= ((int)mem % 32);

is not defined, as *mem has no "intrinsic size".

There may be compilers out there (hello, gcc !) which allow this as an extension, but in general, you can only do pointer arithmetics on pointers of types which have a size, such as char * , int * etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM