Increment Void Pointer by One Byte? by Two

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



Leave a reply



Submit