Reputation:
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
Upvotes: 0
Views: 273
Reputation: 476960
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.
Upvotes: 2
Reputation: 91017
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.
Upvotes: 2