Increment void pointer by one byte? by two?
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;
Why does incrementing a void pointer by 1 moves one byte ahead but it's 4 bytes for an integer pointer,8 for double?
You can't do pointer arithmetic on a void pointer (because it doesn't make sense). Probably it's just that your compiler has an extension that allows pointer arithmetic to be performed on void pointers, and it's implemented like this. However, it is neither standard nor encouraged to be used.
incrementing a void pointer
1) it doesn't, 2) that's undefined behaviour. void
is an incomplete type, so it doesn't have a well-defined size, so you cannot do pointer arithmetic with its pointers.
Typically you will want char
pointers for byte-wise memory fiddling.
If you compile with all compiler warnings enabled, you will spot such problematic code.
Why does the + 1 operator increment by 2 bytes while ++ increments by 1, in C?
I found the problem. I was running a 64-bit kernel image on a 32-bit QEMU emulator. Once I cross-compiled all the assembly and C source using a 32 compiler, I am able to see everything working as expected.
How to make a pointer increment by 1 byte, not 1 unit
I'd suggest you to create a pointer of char and use it to transverse your struct.
char *ptr = (char*) opt;
++ptr; // will increment by one byte
when you need to restore your struct again, from ptr, just do the usual cast:
opt = (tcp_option_t *) ptr;
Related Topics
Std::Copy to Std::Cout for Std::Pair
Is It Safe to Read an Integer Variable That's Being Concurrently Modified Without Locking
Returning Std::String/Std::List from Dll
How to Forward Declare a Template Class in Namespace Std
Compile Lua Code, Store Bytecode Then Load and Execute It
Platform-Independent Guid Generation in C++
Check If One String Is a Prefix of Another
Is Returning with 'Std::Move' Sensible in the Case of Multiple Return Statements
How Can Std::Bitset Be Faster Than Std::Vector<Bool>
Load an Pem Encoded X.509 Certificate into Windows Cryptoapi
Lru Implementation in Production Code
Converting Between C++ Std::Vector and C Array Without Copying
C++, How to Call a Constructor Directly, Without New
When Do I Use Fabs and When Is It Sufficient to Use Std::Abs