I have a void pointer called ptr
. I want to increment this value by a number of bytes. Is there a way to do this?
Please note that I want to do this in-place without creating any more variables.
Could I do something like ptr = (void *)(++((char *) ptr));
?
You cannot perform arithmetic on a void pointer because pointer arithmetic is defined in terms of the size of the pointed-to object. shouldn't that be reinterpret_cast? @Balk: static_cast is sufficient.
The size of void pointer varies system to system. If the system is 16-bit, size of void pointer is 2 bytes. If the system is 32-bit, size of void pointer is 4 bytes. If the system is 64-bit, size of void pointer is 8 bytes.
You can use the strcmp function to help you compare const char* strings. Then after that you called GetType function, now you know to which type to convert or cast the void pointer of the Object and then do whatever you want with the current iterated object!
A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typcasted to any type. // typecasted to any type like int *, char *, ..
You can cast the pointer to ( char *) to do so. In gcc there is an extension which treats the size of a void as 1. so one can use arithematic on a void* to add an offset in bytes, but using it would yield non-portable code. Show activity on this post.
You cannot perform arithmetic on a void pointer because pointer arithmetic is defined in terms of the size of the pointed-to object. You can, however, cast the pointer to a char*, do arithmetic on that pointer, and then convert it back to a void*:
Then, incrementing the pointer means incrementing the address by 8. In other words, the pointer should always point to the next portion of the memory that contains the next element of the type. So, when you point to char, then the increment will be one. When you point to the 32-
You cannot perform arithmetic on a void pointer because pointer arithmetic is defined in terms of the size of the pointed-to object.
You can, however, cast the pointer to a char*
, do arithmetic on that pointer, and then convert it back to a void*
:
void* p = /* get a pointer somehow */; // In C++: p = static_cast<char*>(p) + 1; // In C: p = (char*)p + 1;
No arithmeatic operations can be done on void
pointer.
The compiler doesn't know the size of the item(s) the void
pointer is pointing to. You can cast the pointer to (char *
) to do so.
In gcc there is an extension which treats the size of a void
as 1
. so one can use arithematic on a void*
to add an offset in bytes, but using it would yield non-portable code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With